The personal finance app for everyone (by everyone)
Ruby
Enable Banking: anchor a posted-only balance when the bank returns a pending-inclusive one (#5100)
arnaurodondevf3f30882cf84
diff --git a/app/models/enable_banking_account/processor.rb b/app/models/enable_banking_account/processor.rbindex a0a4d6c19d..09fbe5f5f9 100644--- a/app/models/enable_banking_account/processor.rb+++ b/app/models/enable_banking_account/processor.rb@@ -24,6 +24,8 @@ class EnableBankingAccount::Processortransactions_ok = process_transactionsif anchor_balance+ move_pending_adjusted_anchor_forward(date)+result = enable_banking_account.current_account.set_current_balance(anchor_balance,date: date,@@ -31,7 +33,11 @@ class EnableBankingAccount::Processor)raise ProcessingError.new("Failed to set current balance: #{result.error}") unless result.success?- enable_banking_account.update!(balance_verified: enable_banking_account.balance_evidence_verified?)+ # The anchor now holds this balance and this sync's pending adjustment.+ enable_banking_account.update!(+ balance_verified: enable_banking_account.balance_evidence_verified?,+ anchor_pending_total: enable_banking_account.pending_total+ )endrescue StandardError => eRails.logger.error "EnableBankingAccount::Processor - Failed to process account #{enable_banking_account.id}: #{e.message}"@@ -51,6 +57,35 @@ class EnableBankingAccount::Processorprivate+ # A previous day's anchor is normally kept as a reconciliation waypoint, which+ # Balance::ReverseCalculator treats as that day's closing balance. An anchor+ # that had pending payments added back (see+ # EnableBankingItem::Importer#pending_balance_adjustment) is only that day's+ # closing balance if none of them books dated on or before that day, which+ # is not known when it is written. Such an anchor is moved forward in place+ # instead, so history before it comes from the booked entries.+ #+ # Account::CurrentBalanceManager's ledger check does not cover it: a pending+ # entry claimed in place by its booked row keeps its created_at, so it counts+ # as already in the anchor although the anchor left it out.+ #+ # The check is on the size of the pending rows counted (anchor_pending_total),+ # so an expected balance whose pending inflows and outflows cancel out is+ # moved forward too. An unknown total (nil) is treated the same way: the+ # anchor may include pending. That is an anchor written before the upgrade+ # or by an earlier link, an available or expected balance stored with+ # pending sync off, or one whose pending rows were not all fetched. Only an+ # anchor known to count no pending rows (zero) can become a waypoint.+ def move_pending_adjusted_anchor_forward(date)+ return if enable_banking_account.anchor_pending_total&.zero?++ entry = enable_banking_account.current_account.valuations.current_anchor.includes(:entry)+ .map(&:entry).max_by { |e| [ e.date, e.created_at, e.id ] }+ # A same-day anchor is updated in place by set_current_balance anyway, and+ # a newer one is left for set_current_balance to judge.+ entry.update!(date: date) if entry && entry.date < date+ end+def process_account!if enable_banking_account.current_account.blank?Rails.logger.error("Enable Banking account #{enable_banking_account.id} has no associated Account")diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rbindex d7ecfa7086..f708ee0fff 100644--- a/app/models/enable_banking_item/importer.rb+++ b/app/models/enable_banking_item/importer.rb@@ -71,6 +71,18 @@ 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+ # Balances that already count pending transactions. Sure keeps pending entries+ # out of balance history, so the pending amounts are added back before such a+ # balance becomes the current anchor (see pending_balance_adjustment). An+ # interim available balance deducts authorised card payments and other holds,+ # but not pending incoming money: Revolut reports only ITAV, and it counts its+ # pending card payments. Expected balances count pending items in both+ # directions. A closing available balance (CLAV) is left out: it can be as of+ # the previous close, before today's authorisations.+ # Pre-normalized like FRESHNESS_BALANCE_TYPES.+ AVAILABLE_BALANCE_TYPES = %w[itav interimavailable].freeze+ EXPECTED_BALANCE_TYPES = %w[xpcd expected].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")@@ -358,12 +370,40 @@ class EnableBankingItem::Importer# DBIT indicates a negative balance (money owed/withdrawn).parsed_amount = -parsed_amount if indicator == "DBIT"+ # Without this sync's pending rows a pending-inclusive balance cannot be+ # made posted-only. Storing the bank's figure would replace a correct+ # anchor and, the next day, leave it behind as a waypoint that includes+ # pending, so the previous anchor is kept until a sync gets both.+ if pending_adjustment_unknown?(enable_banking_account, balance)+ Rails.logger.warn "EnableBankingItem::Importer - Keeping the previous balance for account #{enable_banking_account.uid}: the transaction fetch failed, so the pending payments in its #{balance[:balance_type]} balance are unknown"+ mark_balance_unavailable(enable_banking_account)+ return false+ end++ # pending_total is what the processor checks before the anchor becomes a+ # waypoint: the size of every pending row returned in the balance's+ # currency, counted or not. Inflows an available balance leaves out still+ # move the posted balance once they book, and an inflow and an outflow that+ # cancel out still count. nil when the pending rows are not known,+ # including when the ASPSP rejected the PDNG request or a transaction+ # fetch stopped before its last page: the rows returned are still added+ # back, but others may be missing.+ pending_flows = pending_balance_flows(enable_banking_account, balance, counted_only: false)+ pending_total = pending_flows&.sum(BigDecimal("0"), &:abs)+ # Such a balance is not vouched for either, so the next sync's tiebreak+ # does not start from it (see balance_by_anchor).+ pending_unknown = pending_adjusted?(enable_banking_account, balance) && pending_set_incomplete.include?(enable_banking_account.id)+ pending_total = nil if pending_unknown++ current_balance = parsed_amount + pending_balance_adjustment(enable_banking_account, balance).to_d+# Skipped when the account was unlinked and ignored during the fetch.written = enable_banking_account.write_unless_ignored doenable_banking_account.update!(- current_balance: parsed_amount,+ current_balance: current_balance,+ pending_total: pending_total,currency: balance_currency(balance) || enable_banking_account.currency,- balance_evidence_verified: tiebreak_stage.nil? || VERIFIED_TIEBREAK_STAGES.include?(tiebreak_stage)+ balance_evidence_verified: !pending_unknown && (tiebreak_stage.nil? || VERIFIED_TIEBREAK_STAGES.include?(tiebreak_stage)))end# Only now is the chosen-currency balance known to be the one in use.@@ -443,6 +483,74 @@ class EnableBankingItem::Importer)end+ def pending_rows_by_account+ @pending_rows_by_account ||= {}+ end++ # Balance history is built from posted entries only (pending ones are+ # excluded from balance flows), so the current anchor has to be a posted-only+ # figure too. Returns what to add to an interim available or expected+ # balance to get there (see pending_balance_flows).+ def pending_balance_adjustment(enable_banking_account, balance)+ pending_balance_flows(enable_banking_account, balance)&.sum(BigDecimal("0"))+ end++ # The pending rows this sync's transaction fetch returned that the balance+ # counts (or, with counted_only: false, all of them in its currency), with+ # the sign their entries get (see pending_flow_amount). A pending outflow+ # adds its amount back. A pending inflow subtracts it, for expected balances+ # only. Empty for a balance that does not count pending:+ # booked balances and liability accounts. nil when it does but the pending+ # rows are not fetched, with pending sync off (see pending_adjustment_unknown?+ # for a failed transaction fetch).+ def pending_balance_flows(enable_banking_account, balance, counted_only: true)+ return [] unless pending_adjusted?(enable_banking_account, balance)+ return nil unless include_pending?++ # The currency the balance is stored in, and each row's entry is recorded+ # in (see EnableBankingEntry::Processor#currency).+ currency = balance_currency(balance) || enable_banking_account.currency+ flows = pending_rows_by_account[enable_banking_account.id].to_a.filter_map do |tx|+ tx_currency = parse_currency(tx.dig(:transaction_amount, :currency)) || parse_currency(tx[:currency])+ next unless currency.nil? || tx_currency.nil? || tx_currency == currency++ pending_flow_amount(tx)+ end+ return flows unless counted_only && AVAILABLE_BALANCE_TYPES.include?(normalize_balance_type(balance[:balance_type]))++ flows.select(&:positive?)+ end++ # True when the balance would be adjusted but this sync has no pending rows+ # to adjust it with, because its transaction fetch did not succeed. With+ # pending sync off the rows are never fetched, so the bank's figure is used.+ def pending_adjustment_unknown?(enable_banking_account, balance)+ include_pending? &&+ pending_adjusted?(enable_banking_account, balance) &&+ !pending_rows_by_account.key?(enable_banking_account.id)+ end++ # An interim available or expected balance of an asset account.+ def pending_adjusted?(enable_banking_account, balance)+ pending_adjusted_type?(balance) &&+ enable_banking_account.current_account&.accountable&.classification == "asset"+ end++ def pending_adjusted_type?(balance)+ type = normalize_balance_type(balance[:balance_type])+ AVAILABLE_BALANCE_TYPES.include?(type) || EXPECTED_BALANCE_TYPES.include?(type)+ end++ # The amount a pending row's entry gets (EnableBankingEntry::Processor#amount_value):+ # outflows positive, inflows negative. An unidentified card hold is an+ # outflow even when the ASPSP labels it CRDT.+ def pending_flow_amount(tx)+ amount = signed_transaction_amount(tx)+ return amount unless amount && EnableBankingEntry::Processor.unidentified_hold?(tx)++ amount.abs+ end+# The flag only changes how a credit card's balance is read (see# EnableBankingAccount::Processor#process_account!), so any other linked# account stays booked-first even if the flag is still set from an earlier link.@@ -578,9 +686,14 @@ class EnableBankingItem::Importer# 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.+ #+ # Also skipped when the anchor counted pending rows (anchor_pending_total+ # above zero): one that has since booked dated before the anchor's day is+ # in neither sum, so the expectation would be off by it.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)+ return nil if enable_banking_account.anchor_pending_total&.positive?anchor_date = account.current_anchor_dateflows = booked.map { |tx| [ raw_transaction_date(tx), tx ] }@@ -595,9 +708,18 @@ class EnableBankingItem::Importerlater_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)+ # The anchor is posted-only, the candidates are the bank's figures: the+ # same type, so the same pending adjustment applies to each of them.+ adjustment = pending_balance_adjustment(enable_banking_account, candidates.first).to_d+ # An anchor with an unknown total may be the bank's own figure (written+ # before the upgrade, or with pending sync off), which already deducts+ # pending: the adjustment would count it twice.+ return nil if enable_banking_account.anchor_pending_total.nil? && adjustment.nonzero?++ expected = account.current_anchor_balance - adjustment+ closest = matching_balances(candidates, expected - later_flows)return nil if closest.empty?- return nil unless closest == matching_balances(candidates, account.current_anchor_balance - all_flows)+ return nil unless closest == matching_balances(candidates, expected - all_flows)return [ closest.first, :anchor ] if closest.one?latest = closest.filter_map { |balance| [ balance, parse_balance_timestamp(balance[:last_change_date_time]) ] }@@ -954,6 +1076,9 @@ class EnableBankingItem::Importer)rescue Provider::EnableBanking::EnableBankingError => eraise unless [ :validation_error, :bad_request ].include?(e.error_type)+ # The pending set is unknown, so the balance's pending total is too+ # (see fetch_and_update_balance).+ pending_set_incomplete << enable_banking_account.idapi_error = e.response_data.is_a?(Hash) ? (e.response_data[:error] || e.response_data["error"]) : nilRails.logger.warn "EnableBankingItem::Importer - ASPSP does not support PDNG transaction status for account #{enable_banking_account.uid}, skipping pending transactions. API error: #{api_error || e.message}"capture_pdng_unsupported_debug_log(enable_banking_account, error: e)@@ -988,6 +1113,21 @@ class EnableBankingItem::Importer# Remove content-level duplicates before storing. (Issue #954)all_transactions = deduplicate_api_transactions(all_transactions)+ # The pending rows the bank reports right now, which pending_balance_adjustment+ # adds back to a pending-inclusive balance. Taken before the date filter:+ # the bank's balance counts every one of them. Rows are tagged _pending+ # only when pending sync is on. A pending row from the booked response+ # whose booked row came back too has settled, as for the PDNG rows above.+ # Recorded below, once the transactions are stored.+ pending_rows =+ all_transactions.map(&:with_indifferent_access).select do |tx|+ next false unless tx[:_pending]++ fp = EnableBankingEntry::Processor.compute_external_id(tx)+ entry_ref = tx[:entry_reference].presence+ !((fp.present? && book_fingerprints.include?(fp)) || (entry_ref.present? && book_entry_refs.include?(entry_ref)))+ end+# Post-fetch safety filter: some ASPSPs ignore date_from or return extra transactionsall_transactions = filter_transactions_by_date(all_transactions, start_date)@@ -1083,6 +1223,10 @@ class EnableBankingItem::Importerendend+ # Only now: a fetch or snapshot write that raised leaves no rows for the+ # account, so its balance is withheld (see pending_adjustment_unknown?).+ pending_rows_by_account[enable_banking_account.id] = pending_rows+{ success: true, transactions_count: transactions_count, truncated: truncated }rescue Provider::EnableBanking::EnableBankingError => eRails.logger.error "EnableBankingItem::Importer - Error fetching transactions for account #{enable_banking_account.uid}: #{e.message}"@@ -1176,6 +1320,7 @@ class EnableBankingItem::Importer# Returns the rows fetched and whether the fetch stopped before the last# page (page cap, repeated continuation key, or a 400/422 on a later page).+ # A partial result also leaves the account's pending set incomplete.def fetch_paginated_transactions(enable_banking_account, start_date:, transaction_status:, psu_headers: {}, strategy: nil)all_transactions = []truncated = false@@ -1231,6 +1376,7 @@ class EnableBankingItem::Importertransactions_kept: all_transactions.count,error: e)+ pending_set_incomplete << enable_banking_account.idtruncated = truebreakend@@ -1254,12 +1400,19 @@ class EnableBankingItem::Importer# Log as warning and return collected partial data instead of failing entirely.# This ensures accounts with huge history don't lose all synced data.Rails.logger.warn(e.message)+ pending_set_incomplete << enable_banking_account.idif strategy.present?capture_longest_truncation_debug_log(enable_banking_account, transactions_kept: all_transactions.count, reason: e.message)end[ all_transactions, true ]end+ # Accounts whose pending rows this sync may not all have seen: the ASPSP+ # rejected the PDNG request, or a transaction fetch kept a partial result.+ def pending_set_incomplete+ @pending_set_incomplete ||= Set.new+ end+# Ids are resolved over stored and fetched rows together so rows sharing a# transaction_id can still be told apart by entry_reference.def external_ids_by_row(rows)diff --git a/db/migrate/20261118090000_add_pending_totals_to_enable_banking_accounts.rb b/db/migrate/20261118090000_add_pending_totals_to_enable_banking_accounts.rbnew file mode 100644index 0000000000..ecf8ce7d46--- /dev/null+++ b/db/migrate/20261118090000_add_pending_totals_to_enable_banking_accounts.rb@@ -0,0 +1,6 @@+class AddPendingTotalsToEnableBankingAccounts < ActiveRecord::Migration[8.1]+ def change+ add_column :enable_banking_accounts, :pending_total, :decimal, precision: 19, scale: 4+ add_column :enable_banking_accounts, :anchor_pending_total, :decimal, precision: 19, scale: 4+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex c69bc1082c..4e666ea235 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -628,6 +628,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) dot.string "account_id"t.string "account_status"t.string "account_type"+ t.decimal "anchor_pending_total", precision: 19, scale: 4t.boolean "balance_evidence_verified", default: false, null: falset.boolean "balance_verified", default: false, null: falset.datetime "created_at", null: false@@ -641,6 +642,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_21_110000) dot.boolean "ignored", default: false, null: falset.jsonb "institution_metadata"t.string "name"+ t.decimal "pending_total", precision: 19, scale: 4t.string "product"t.string "provider"t.jsonb "raw_payload"diff --git a/test/models/enable_banking_item/importer_balance_test.rb b/test/models/enable_banking_item/importer_balance_test.rbindex 4b5d93e8b1..cc70197271 100644--- a/test/models/enable_banking_item/importer_balance_test.rb+++ b/test/models/enable_banking_item/importer_balance_test.rb@@ -27,6 +27,10 @@ class EnableBankingItem::ImporterBalanceTest < ActiveSupport::TestCase@mock_provider = OpenStruct.new@importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ # These tests run the balance step on its own. With pending sync on, an+ # available or expected balance also needs the transaction step that runs+ # before it in a sync (see importer_pending_balance_test.rb).+ @importer.stubs(:include_pending?).returns(false)endtest "FRESHNESS_BALANCE_TYPES only lists normalized spellings that BALANCE_TYPE_PRIORITY itself accepts" dodiff --git a/test/models/enable_banking_item/importer_pending_balance_test.rb b/test/models/enable_banking_item/importer_pending_balance_test.rbnew file mode 100644index 0000000000..cf6843c567--- /dev/null+++ b/test/models/enable_banking_item/importer_pending_balance_test.rb@@ -0,0 +1,906 @@+require "test_helper"++# A bank that reports only an available (ITAV) balance has already deducted its+# pending card payments. Sure builds balance history from posted entries only, so+# the importer adds those pending payments back before the balance becomes the+# current anchor. Booked balances are already posted-only and stay as reported.+class EnableBankingItem::ImporterPendingBalanceTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @enable_banking_item = EnableBankingItem.create!(+ family: @family,+ name: "Revolut",+ country_code: "LT",+ 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: "Main",+ uid: "identification_hash_pending",+ account_id: "22222222-2222-2222-2222-222222222222",+ currency: "EUR",+ account_status: "active",+ provider: "enable_banking"+ )++ @account = Account.create!(+ family: @family,+ name: "Revolut Main",+ balance: 0,+ cash_balance: 0,+ currency: "EUR",+ accountable: Depository.create!+ )+ AccountProvider.create!(account: @account, provider: @enable_banking_account)+ @enable_banking_account.reload++ @mock_provider = OpenStruct.new+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(true)+ end++ test "an available balance gets this sync's pending card payments added back" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ end++ test "the descriptive interimAvailable spelling is treated the same way" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "20.00"), pending_tx("card_2", "5.50") ])+ stub_balances(balance("interimAvailable", "74.50"))++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ end++ test "the descriptive expected spelling is treated like XPCD" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "10.00"), pending_tx("incoming_1", "4.00", indicator: "CRDT") ])+ stub_balances(balance("expected", "94.00"))++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ end++ test "a pending row without a currency is added back" do+ card = pending_tx("card_1", "36.01")+ card[:transaction_amount] = { amount: "36.01" }+ stub_transactions(booked: [], pending: [ card ])+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ end++ test "a balance without a currency gets the pending rows added back" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ itav = balance("ITAV", "64.53")+ itav[:balance_amount] = { amount: "64.53" }+ stub_balances(itav)++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ end++ test "a booked balance stays as reported when the bank also sends pending rows" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("ITBD", "100.54"), balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ end++ test "a closing booked balance stays as reported" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("CLBD", "100.54"))++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ end++ test "an available balance does not count pending incoming money" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "10.00"), pending_tx("refund_1", "4.00", indicator: "CRDT") ])+ stub_balances(balance("ITAV", "90.00"))++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ end++ test "an expected balance has pending items in both directions reversed" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "10.00"), pending_tx("incoming_1", "4.00", indicator: "CRDT") ])+ stub_balances(balance("XPCD", "94.00"))++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ end++ test "a pending row that settles in the same sync is not added back" do+ settled = pending_tx("card_1", "36.01").merge(status: "BOOK")+ stub_transactions(booked: [ settled ], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ end++ test "a pending row in the booked response is not added back when its booked row came too" do+ salary = booked_tx("salary_1", "150.00", date: (Date.current - 5).to_s, indicator: "CRDT")+ pending_copy = pending_tx("card_1", "36.01", date: (Date.current - 1).to_s)+ booked_copy = booked_tx("card_1", "36.01", date: Date.current.to_s)+ stub_transactions(booked: [ salary, pending_copy, booked_copy ], pending: [])+ stub_balances(balance("ITAV", "113.99"))++ sync_balance++ assert_equal BigDecimal("113.99"), @enable_banking_account.reload.current_balance+ end++ test "a settled pending row in the booked response is matched by id or by entry reference" do+ salary = booked_tx("salary_1", "150.00", date: (Date.current - 5).to_s, indicator: "CRDT")+ # Gains a transaction_id when it books; the entry_reference stays.+ by_reference = pending_tx("card_r", "10.00", date: (Date.current - 1).to_s).merge(transaction_id: nil)+ by_reference_booked = booked_tx("card_r", "10.00", date: Date.current.to_s)+ # Keeps its transaction_id; the entry_reference changes.+ by_id = pending_tx("card_i", "5.00", date: (Date.current - 1).to_s)+ by_id_booked = booked_tx("card_i", "5.00", date: Date.current.to_s).merge(entry_reference: "ref_card_i_booked")+ stub_transactions(booked: [ salary, by_reference, by_reference_booked, by_id, by_id_booked ], pending: [])+ stub_balances(balance("ITAV", "135.00"))++ sync_balance++ assert_equal BigDecimal("135.00"), @enable_banking_account.reload.current_balance+ end++ test "pending rows in another currency are not added back" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01", currency: "USD") ])+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ end++ # Through the freshness rule, an available balance dated after a period+ # boundary balance is picked over it, so it is adjusted like an ITAV-only one.+ test "an available balance picked over an older PRCD or OPBD balance gets pending added back" do+ %w[PRCD OPBD].each do |boundary|+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(+ balance(boundary, "150.00", reference_date: (Date.current - 1).to_s),+ balance("ITAV", "64.53", reference_date: Date.current.to_s)+ )++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance, boundary+ assert_equal BigDecimal("36.01"), @enable_banking_account.pending_total, boundary+ end+ end++ test "a PRCD balance an available balance does not replace stays as reported" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(+ balance("PRCD", "150.00", reference_date: Date.current.to_s),+ balance("ITAV", "64.53", reference_date: Date.current.to_s)+ )++ sync_balance++ assert_equal BigDecimal("150.00"), @enable_banking_account.reload.current_balance+ assert_equal BigDecimal("0"), @enable_banking_account.pending_total+ end++ test "a closing available balance stays as reported" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("CLAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ end++ test "an unidentified card hold labelled CRDT is added back as the outflow its entry records" do+ stub_transactions(booked: [ unidentified_hold("20.00") ], pending: [])+ stub_balances(balance("ITAV", "80.00"))++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ end++ test "an expected balance reverses an unidentified card hold labelled CRDT as an outflow" do+ stub_transactions(booked: [ unidentified_hold("20.00") ], pending: [])+ stub_balances(balance("XPCD", "80.00"))++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ end++ test "the balance stays as reported when pending transactions are not synced" do+ @importer.stubs(:include_pending?).returns(false)+ # The bank returns pending rows in the booked response too; with pending+ # sync off they are dropped, so none of them is added back.+ in_booked = pending_tx("card_2", "10.00")+ stub_transactions(booked: [ in_booked, unidentified_hold("20.00") ], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ assert_nil @enable_banking_account.pending_total+ end++ test "an available balance is not stored when the pending fetch fails after the booked one" do+ # The booked response already carries one pending row, but the full pending+ # set is unknown once the PDNG fetch fails.+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [ pending_tx("card_2", "10.00") ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG"))+ .raises(Provider::EnableBanking::EnableBankingError.new("boom", :request_failed))+ stub_balances(balance("ITAV", "64.53"))+ # A figure left from an earlier fetch must not be written as the anchor.+ @enable_banking_account.update_columns(current_balance: 50)++ @importer.send(:fetch_and_store_transactions, @enable_banking_account)+ assert_not @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_nil @enable_banking_account.reload.current_balance+ end++ test "an available balance is not stored when the transactions cannot be saved" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("ITAV", "64.53"))+ @enable_banking_account.update_columns(current_balance: 50)+ @enable_banking_account.stubs(:upsert_enable_banking_transactions_snapshot!).raises(ActiveRecord::StatementInvalid, "boom")++ assert_not @importer.send(:fetch_and_store_transactions, @enable_banking_account)[:success]+ assert_not @importer.send(:fetch_and_update_balance, @enable_banking_account)++ assert_nil @enable_banking_account.reload.current_balance+ end++ test "a booked balance is still stored when the transaction fetch fails" do+ @importer.stubs(:fetch_paginated_transactions).raises(Provider::EnableBanking::EnableBankingError.new("slow down", :rate_limited))+ stub_balances(balance("CLBD", "100.54"))++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ end++ test "with pending sync off an available balance is still stored when the transaction fetch fails" do+ @importer.stubs(:include_pending?).returns(false)+ @importer.stubs(:fetch_paginated_transactions).raises(Provider::EnableBanking::EnableBankingError.new("slow down", :rate_limited))+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ end++ test "a liability balance is still stored when the transaction fetch fails" do+ @account.update!(accountable: CreditCard.create!)+ @enable_banking_account.reload+ @importer.stubs(:fetch_paginated_transactions).raises(Provider::EnableBanking::EnableBankingError.new("slow down", :rate_limited))+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ end++ test "a pending row dated before the sync window is still added back" do+ @enable_banking_item.update!(sync_start_date: Date.current - 5)+ stub_transactions(booked: [], pending: [ pending_tx("card_old", "36.01", date: (Date.current - 30).to_s) ])+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ assert_empty @enable_banking_account.raw_transactions_payload.to_a, "the row itself is outside the window"+ end++ test "a pending fetch cut short after its first page leaves the pending total unknown" do+ page_error = Provider::EnableBanking::EnableBankingError.new("bad continuation key", :bad_request)+ pages = 0+ @mock_provider.define_singleton_method(:get_account_transactions) do |transaction_status:, **|+ next { transactions: [] } if transaction_status == "BOOK"++ pages += 1+ raise page_error if pages > 1++ { transactions: [ { entry_reference: "ref_card_1", transaction_id: "txn_card_1", booking_date: Date.current.to_s,+ transaction_amount: { amount: "10.00", currency: "EUR" }, credit_debit_indicator: "DBIT",+ remittance_information: [ "Merchant card_1" ], status: "PDNG" } ],+ continuation_key: "page_2" }+ end+ stub_balances(balance("ITAV", "70.00"))++ sync_balance++ assert_equal BigDecimal("80.00"), @enable_banking_account.reload.current_balance+ assert_nil @enable_banking_account.pending_total, "the second page's pending rows are unknown"+ end++ test "a pending fetch stopped on a repeated continuation key leaves the pending total unknown" do+ @mock_provider.define_singleton_method(:get_account_transactions) do |transaction_status:, **|+ next { transactions: [] } if transaction_status == "BOOK"++ { transactions: [], continuation_key: "same_key" }+ end+ stub_balances(balance("ITAV", "70.00"))++ sync_balance++ assert_nil @enable_banking_account.reload.pending_total+ end++ test "a balance without a currency only counts pending rows in the account's currency" do+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "10.00"), pending_tx("card_usd", "20.00", currency: "USD") ])+ itav = balance("ITAV", "90.00")+ itav[:balance_amount] = { amount: "90.00" }+ stub_balances(itav)++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ assert_equal BigDecimal("10.00"), @enable_banking_account.pending_total+ end++ test "a pending row with its currency at the top level is matched on it" do+ usd = pending_tx("card_usd", "20.00").except(:transaction_amount).merge(amount: "20.00", currency: "USD")+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "10.00"), usd ])+ stub_balances(balance("ITAV", "90.00"))++ sync_balance++ assert_equal BigDecimal("100.00"), @enable_banking_account.reload.current_balance+ end++ test "a rejected pending request leaves an available balance's pending total unknown" do+ # The booked response still carries one pending row, which is added back.+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [ pending_tx("card_2", "10.00") ], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG"))+ .raises(Provider::EnableBanking::EnableBankingError.new("unsupported", :validation_error))+ stub_balances(balance("ITAV", "54.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ assert_nil @enable_banking_account.pending_total, "other pending rows may be missing, so the anchor must not become a waypoint"+ end++ test "a booked fetch cut short leaves an available balance's pending total unknown" do+ page_error = Provider::EnableBanking::EnableBankingError.new("bad continuation key", :validation_error)+ pages = 0+ @mock_provider.define_singleton_method(:get_account_transactions) do |transaction_status:, **|+ next { transactions: [] } if transaction_status == "PDNG"++ pages += 1+ raise page_error if pages > 1++ { transactions: [], continuation_key: "page_2" }+ end+ stub_balances(balance("ITAV", "70.00"))++ sync_balance++ assert_equal BigDecimal("70.00"), @enable_banking_account.reload.current_balance+ assert_nil @enable_banking_account.pending_total+ end++ # With the PDNG request rejected and the pending payment absent from the+ # booked response, nothing tells the importer the balance includes it. The+ # balance is stored as the bank reports it, so history is low by the payment+ # while it is pending, as on main. Its unknown pending total keeps the anchor+ # from becoming a waypoint, so history is right once the payment books.+ test "with the pending request rejected history is off while a payment is pending and right once it books" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")+ rejected = Provider::EnableBanking::EnableBankingError.new("unsupported", :validation_error)+ sync = lambda do |booked|+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(true)+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ booked, false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG")).raises(rejected)+ # ITAV already deducts the card payment of 36.01 pending at the 08-25 sync.+ stub_balances(balance("ITAV", "80.99"))+ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process+ Balance::Materializer.new(Account.find(@account.id), strategy: :reverse).materialize_balances+ %w[2026-08-23 2026-08-24 2026-08-25].index_with { |date| @account.balances.find_by(date: Date.parse(date))&.end_balance&.to_s("F") }+ end++ travel_to Time.zone.local(2026, 8, 25, 9) do+ assert_equal({ "2026-08-23" => "113.99", "2026-08-24" => "80.99", "2026-08-25" => "80.99" }, sync.call([ salary, lunch ]))+ assert_nil @enable_banking_account.reload.pending_total+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ # Booked the next day, so a waypoint left at 80.99 on 08-25 would show.+ card = booked_tx("card_1", "36.01", date: "2026-08-26")+ assert_equal({ "2026-08-23" => "150.0", "2026-08-24" => "117.0", "2026-08-25" => "117.0" }, sync.call([ salary, lunch, card ]))+ end+ assert_empty @account.valuations.reconciliation+ end++ test "an available balance with a rejected pending request is not vouched for as the next anchor" do+ stub_transactions(booked: [], pending: [])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG"))+ .raises(Provider::EnableBanking::EnableBankingError.new("unsupported", :validation_error))+ stub_balances(balance("ITAV", "64.53"))++ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process++ assert_not @enable_banking_account.reload.balance_evidence_verified?+ assert_not @enable_banking_account.balance_verified?, "the next sync's tiebreak must not start from this anchor"+ end++ test "a rejected pending request leaves a booked balance's pending total at zero" do+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ [], false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG"))+ .raises(Provider::EnableBanking::EnableBankingError.new("unsupported", :bad_request))+ stub_balances(balance("CLBD", "100.54"))++ sync_balance++ assert_equal BigDecimal("100.54"), @enable_banking_account.reload.current_balance+ assert_equal BigDecimal("0"), @enable_banking_account.pending_total+ end++ test "the same-type tiebreak compares the anchor with the bank's figures plus pending" do+ create_anchor(100, Date.current - 2)+ @enable_banking_account.update!(balance_verified: true, anchor_pending_total: 0)+ yesterday = booked_tx("coffee_1", "10.00", date: (Date.current - 1).to_s)+ stub_transactions(booked: [ yesterday ], pending: [ pending_tx("card_1", "20.00") ])+ # Posted: 100 - 10 = 90. The bank deducts the 20 pending, so 70 is right.+ stub_balances(balance("ITAV", "90.00"), balance("ITAV", "70.00"))++ sync_balance++ assert_equal BigDecimal("90.00"), @enable_banking_account.reload.current_balance+ assert_equal BigDecimal("20.00"), @enable_banking_account.pending_total+ assert @enable_banking_account.balance_evidence_verified?+ assert_equal "anchor", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ # A payment pending at the anchor that books dated before the anchor's day+ # falls outside the bookings the check counts, yet the anchor had it added+ # back. The expected balance is then off by it and could match the wrong figure.+ test "the same-type tiebreak does not use an anchor that had pending rows" do+ create_anchor(117, Date.current - 1)+ @enable_banking_account.update!(balance_verified: true, anchor_pending_total: BigDecimal("36.01"))+ card = booked_tx("card_1", "36.01", date: (Date.current - 2).to_s)+ stub_transactions(booked: [ card ], pending: [])+ # Posted: 117 - 36.01 = 80.99. Counting only bookings from the anchor's day+ # on would expect 117.+ stub_balances(balance("ITAV", "117.00"), balance("ITAV", "80.99"))++ sync_balance++ assert_equal BigDecimal("80.99"), @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++ # An anchor with no recorded total may be the bank's own figure (written+ # before the upgrade, or with pending sync off), which already deducts the+ # pending payment. Subtracting this sync's adjustment from it counts it twice.+ test "the same-type tiebreak does not adjust an anchor with an unknown pending total" do+ create_anchor(80, Date.current - 1)+ @enable_banking_account.update!(balance_verified: true, anchor_pending_total: nil)+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "20.00") ])+ stub_balances(balance("ITAV", "80.00"), balance("ITAV", "60.00"))++ sync_balance++ assert_not @enable_banking_account.reload.balance_evidence_verified?+ assert_equal "lowest", DebugLogEntry.order(:created_at).last.metadata["stage"]+ end++ test "a liability account keeps the bank's figure" do+ @account.update!(accountable: CreditCard.create!)+ @enable_banking_account.reload+ stub_transactions(booked: [], pending: [ pending_tx("card_1", "36.01") ])+ stub_balances(balance("ITAV", "64.53"))++ sync_balance++ assert_equal BigDecimal("64.53"), @enable_banking_account.reload.current_balance+ end++ test "history before a pending payment does not move when the balance includes it" do+ travel_to Date.new(2026, 8, 25) do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ opening = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")+ stub_transactions(booked: [ opening, lunch ], pending: [ pending_tx("card_1", "36.01", date: "2026-08-25") ])+ # 150.00 - 33.00 posted, minus 36.01 still pending.+ stub_balances(balance("ITAV", "80.99"))++ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process+ Balance::Materializer.new(@account.reload, strategy: :reverse).materialize_balances++ assert_equal BigDecimal("117.00"), @account.balances.find_by(date: Date.new(2026, 8, 24)).end_balance+ assert_equal BigDecimal("150.00"), @account.balances.find_by(date: Date.new(2026, 8, 23)).end_balance+ end+ end++ test "history stays right when a pending payment books dated on the day it was pending" do+ assert_history_across_settlement(booked_on: Date.new(2026, 8, 25), expected: {+ Date.new(2026, 8, 23) => "150.00",+ Date.new(2026, 8, 24) => "117.00",+ Date.new(2026, 8, 25) => "80.99",+ Date.new(2026, 8, 26) => "80.99"+ })+ end++ # Account::CurrentBalanceManager's ledger check keeps the pending entry out:+ # its booked row updates it in place, so it keeps the created_at it had before+ # the anchor was written, on the anchor's day.+ test "with the explained-anchor check on history stays right when a pending payment books dated on the day it was pending" do+ Rails.configuration.x.balance.stubs(:reuse_explained_anchor).returns(true)++ assert_history_across_settlement(booked_on: Date.new(2026, 8, 25), expected: {+ Date.new(2026, 8, 23) => "150.00",+ Date.new(2026, 8, 24) => "117.00",+ Date.new(2026, 8, 25) => "80.99",+ Date.new(2026, 8, 26) => "80.99"+ })+ end++ test "history stays right when a pending payment books dated the next day" do+ assert_history_across_settlement(booked_on: Date.new(2026, 8, 26), expected: {+ Date.new(2026, 8, 23) => "150.00",+ Date.new(2026, 8, 24) => "117.00",+ Date.new(2026, 8, 25) => "117.00",+ Date.new(2026, 8, 26) => "80.99"+ })+ end++ test "a later sync whose transaction fetch fails keeps the posted-only anchor" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ sync_and_process(booked: [ salary, lunch ], pending: [ pending_tx("card_1", "36.01", date: "2026-08-25") ], itav: "80.99")+ end++ travel_to Time.zone.local(2026, 8, 25, 18) do+ # Transactions are rate limited, the balance still comes back.+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(true)+ @importer.stubs(:fetch_paginated_transactions).raises(Provider::EnableBanking::EnableBankingError.new("slow down", :rate_limited))+ stub_balances(balance("ITAV", "80.99"))+ @importer.send(:fetch_and_store_transactions, @enable_banking_account)+ assert_not @importer.send(:fetch_and_update_balance, @enable_banking_account)+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process++ assert_equal BigDecimal("117.00"), Account.find(@account.id).current_anchor_balance+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ card = booked_tx("card_1", "36.01", date: "2026-08-26")+ sync_and_process(booked: [ salary, lunch, card ], pending: [], itav: "80.99")+ Balance::Materializer.new(Account.find(@account.id), strategy: :reverse).materialize_balances+ end++ expected = {+ Date.new(2026, 8, 23) => BigDecimal("150.00"),+ Date.new(2026, 8, 24) => BigDecimal("117.00"),+ Date.new(2026, 8, 25) => BigDecimal("117.00"),+ Date.new(2026, 8, 26) => BigDecimal("80.99")+ }+ assert_equal expected, expected.keys.index_with { |date| @account.balances.find_by(date: date)&.end_balance }+ assert_empty @account.valuations.reconciliation+ end++ test "an anchor written before the adjustment was recorded is not kept as a waypoint" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ sync_and_process(booked: [ salary, lunch ], pending: [ pending_tx("card_1", "36.01", date: "2026-08-25") ], itav: "80.99")+ # As written before the upgrade: the bank's figure, nothing recorded.+ @account.valuations.current_anchor.first.entry.update!(amount: 80.99)+ @enable_banking_account.update_columns(pending_total: nil, anchor_pending_total: nil)+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ card = booked_tx("card_1", "36.01", date: "2026-08-26")+ sync_and_process(booked: [ salary, lunch, card ], pending: [], itav: "80.99")+ Balance::Materializer.new(Account.find(@account.id), strategy: :reverse).materialize_balances+ end++ expected = {+ Date.new(2026, 8, 23) => BigDecimal("150.00"),+ Date.new(2026, 8, 24) => BigDecimal("117.00"),+ Date.new(2026, 8, 25) => BigDecimal("117.00"),+ Date.new(2026, 8, 26) => BigDecimal("80.99")+ }+ assert_equal expected, expected.keys.index_with { |date| @account.balances.find_by(date: date)&.end_balance }+ assert_empty @account.valuations.reconciliation+ end++ test "an anchor from a booked balance records no adjustment and still becomes a waypoint" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")++ [ Time.zone.local(2026, 8, 25, 9), Time.zone.local(2026, 8, 26, 9) ].each do |time|+ travel_to time do+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(true)+ stub_transactions(booked: [ salary ], pending: [])+ stub_balances(balance("CLBD", "150.00"))+ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process+ end+ end++ assert_equal BigDecimal("0"), @enable_banking_account.reload.anchor_pending_total+ assert @account.valuations.reconciliation.joins(:entry).exists?(entries: { date: Date.new(2026, 8, 25) })+ end++ test "an anchor stored with pending sync off is not kept as a waypoint once it is turned on" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ sync_and_process(booked: [ salary, lunch ], pending: [ pending_tx("card_1", "36.01", date: "2026-08-25") ], itav: "80.99", include_pending: false)+ assert_nil @enable_banking_account.reload.anchor_pending_total+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ card = booked_tx("card_1", "36.01", date: "2026-08-26")+ sync_and_process(booked: [ salary, lunch, card ], pending: [], itav: "80.99")+ Balance::Materializer.new(Account.find(@account.id), strategy: :reverse).materialize_balances+ end++ expected = {+ Date.new(2026, 8, 23) => BigDecimal("150.00"),+ Date.new(2026, 8, 24) => BigDecimal("117.00"),+ Date.new(2026, 8, 25) => BigDecimal("117.00"),+ Date.new(2026, 8, 26) => BigDecimal("80.99")+ }+ assert_equal expected, expected.keys.index_with { |date| @account.balances.find_by(date: date)&.end_balance }+ assert_empty @account.valuations.reconciliation+ end++ test "an expected balance whose pending items cancel out is not kept as a waypoint" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")+ refund = pending_tx("refund_1", "10.00", indicator: "CRDT", date: "2026-08-25")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(true)+ stub_transactions(booked: [ salary, lunch ], pending: [ pending_tx("card_1", "10.00", date: "2026-08-25"), refund ])+ stub_balances(balance("XPCD", "117.00"))+ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process+ assert_equal BigDecimal("20.00"), @enable_banking_account.reload.anchor_pending_total+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(true)+ card = booked_tx("card_1", "10.00", date: "2026-08-25")+ stub_transactions(booked: [ salary, lunch, card ], pending: [ refund ])+ stub_balances(balance("XPCD", "117.00"))+ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process+ Balance::Materializer.new(Account.find(@account.id), strategy: :reverse).materialize_balances+ end++ expected = {+ Date.new(2026, 8, 23) => BigDecimal("150.00"),+ Date.new(2026, 8, 24) => BigDecimal("117.00"),+ Date.new(2026, 8, 25) => BigDecimal("107.00"),+ Date.new(2026, 8, 26) => BigDecimal("107.00")+ }+ assert_equal expected, expected.keys.index_with { |date| @account.balances.find_by(date: date)&.end_balance }+ assert_empty @account.valuations.reconciliation+ end++ test "an available-balance anchor with only pending incoming money is not kept as a waypoint" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ # ITAV leaves the pending refund out, so nothing is added back.+ sync_and_process(booked: [ salary, lunch ], pending: [ pending_tx("refund_1", "20.00", indicator: "CRDT", date: "2026-08-25") ], itav: "117.00")+ assert_equal BigDecimal("117.00"), Account.find(@account.id).current_anchor_balance+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ refund = booked_tx("refund_1", "20.00", date: "2026-08-25", indicator: "CRDT")+ sync_and_process(booked: [ salary, lunch, refund ], pending: [], itav: "137.00")+ Balance::Materializer.new(Account.find(@account.id), strategy: :reverse).materialize_balances+ end++ expected = {+ Date.new(2026, 8, 23) => BigDecimal("150.00"),+ Date.new(2026, 8, 24) => BigDecimal("117.00"),+ Date.new(2026, 8, 25) => BigDecimal("137.00"),+ Date.new(2026, 8, 26) => BigDecimal("137.00")+ }+ assert_equal expected, expected.keys.index_with { |date| @account.balances.find_by(date: date)&.end_balance }+ assert_empty @account.valuations.reconciliation+ end++ test "a booked-balance anchor still becomes a waypoint when the next balance is adjusted" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(true)+ stub_transactions(booked: [ salary ], pending: [])+ stub_balances(balance("CLBD", "150.00"))+ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ sync_and_process(booked: [ salary ], pending: [ pending_tx("card_1", "10.00", date: "2026-08-26") ], itav: "140.00")+ end++ waypoint = @account.valuations.reconciliation.joins(:entry).find_by(entries: { date: Date.new(2026, 8, 25) })+ assert waypoint, "a booked balance is a posted-only figure, so it stays a waypoint"+ assert_equal BigDecimal("150.00"), waypoint.entry.amount+ end++ test "a liability anchor records no adjustment and still becomes a waypoint" do+ @account.update!(accountable: CreditCard.create!)+ @enable_banking_account.reload++ [ Time.zone.local(2026, 8, 25, 9), Time.zone.local(2026, 8, 26, 9) ].each do |time|+ travel_to time do+ sync_and_process(booked: [], pending: [ pending_tx("card_1", "10.00") ], itav: "64.53")+ end+ end++ assert_equal BigDecimal("0"), @enable_banking_account.reload.anchor_pending_total+ assert @account.valuations.reconciliation.joins(:entry).exists?(entries: { date: Date.new(2026, 8, 25) })+ end++ test "an anchor without pending added back still becomes a waypoint the next day" do+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ sync_and_process(booked: [ salary ], pending: [], itav: "150.00")+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ sync_and_process(booked: [ salary ], pending: [], itav: "150.00")+ end++ waypoint = @account.valuations.reconciliation.joins(:entry).find_by(entries: { date: Date.new(2026, 8, 25) })+ assert waypoint, "a booked-only anchor keeps its waypoint"+ assert_equal BigDecimal("150.00"), waypoint.entry.amount+ end++ private++ # Salary 150 on 08-20 and lunch 33 on 08-24. A card payment of 36.01 is+ # pending at the 08-25 sync (ITAV 80.99 already deducts it) and booked by the+ # 08-26 sync, dated booked_on.+ def assert_history_across_settlement(booked_on:, expected:)+ @enable_banking_item.update!(sync_start_date: Date.new(2026, 8, 1))+ salary = booked_tx("salary_1", "150.00", date: "2026-08-20", indicator: "CRDT")+ lunch = booked_tx("lunch_1", "33.00", date: "2026-08-24")++ travel_to Time.zone.local(2026, 8, 25, 9) do+ sync_and_process(booked: [ salary, lunch ], pending: [ pending_tx("card_1", "36.01", date: "2026-08-25") ], itav: "80.99")+ assert_equal BigDecimal("117.00"), Account.find(@account.id).current_anchor_balance+ end++ travel_to Time.zone.local(2026, 8, 26, 9) do+ card = booked_tx("card_1", "36.01", date: booked_on.to_s)+ sync_and_process(booked: [ salary, lunch, card ], pending: [], itav: "80.99")+ # A fresh record: Account memoizes its current anchor.+ Balance::Materializer.new(Account.find(@account.id), strategy: :reverse).materialize_balances+ end++ actual = expected.keys.index_with { |date| @account.balances.find_by(date: date)&.end_balance }+ assert_equal expected.transform_values { |amount| BigDecimal(amount) }, actual+ assert_empty @account.valuations.reconciliation, "a pending-adjusted anchor must not become a waypoint"+ end++ # One sync: a fresh importer, as each sync builds its own.+ def sync_and_process(booked:, pending:, itav:, include_pending: true)+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @mock_provider)+ @importer.stubs(:include_pending?).returns(include_pending)+ stub_transactions(booked: booked, pending: pending)+ stub_balances(balance("ITAV", itav))+ sync_balance+ EnableBankingAccount::Processor.new(@enable_banking_account.reload).process+ end++ def create_anchor(amount, date)+ @account.entries.create!(+ date: date,+ name: "Current balance",+ amount: amount,+ currency: "EUR",+ entryable: Valuation.new(kind: "current_anchor")+ )+ end++ # An authorisation hold without identifiers or counterparty, which some+ # ASPSPs label CRDT. Sure records it as a pending outflow.+ def unidentified_hold(amount)+ {+ entry_reference: nil,+ transaction_id: nil,+ booking_date: Date.current.to_s,+ transaction_amount: { amount: amount, currency: "EUR" },+ credit_debit_indicator: "CRDT",+ remittance_information: [ "474836xxxxxx6879 003015315475" ],+ status: "BOOK"+ }+ end++ def sync_balance+ @importer.send(:fetch_and_store_transactions, @enable_banking_account)+ assert @importer.send(:fetch_and_update_balance, @enable_banking_account)+ end++ def stub_transactions(booked:, pending:)+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns([ booked, false ])+ @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entries(transaction_status: "PDNG")).returns([ pending, false ])+ end++ def stub_balances(*balances)+ @mock_provider.stubs(:get_account_balances).returns(balances: balances)+ end++ def balance(type, amount, indicator: "CRDT", reference_date: nil)+ {+ balance_type: type,+ balance_amount: { amount: amount, currency: "EUR" },+ credit_debit_indicator: indicator,+ reference_date: reference_date+ }.compact+ end++ def pending_tx(id, amount, indicator: "DBIT", currency: "EUR", date: Date.current.to_s)+ {+ entry_reference: "ref_#{id}",+ transaction_id: "txn_#{id}",+ booking_date: date,+ transaction_amount: { amount: amount, currency: currency },+ credit_debit_indicator: indicator,+ remittance_information: [ "Merchant #{id}" ],+ status: "PDNG"+ }+ end++ def booked_tx(id, amount, date:, indicator: "DBIT")+ pending_tx(id, amount, indicator: indicator, date: date).merge(status: "BOOK")+ end+end