The personal finance app for everyone (by everyone)
Ruby
class EnableBankingAccount::Processor
class ProcessingError < StandardError; end
include CurrencyNormalizable
attr_reader :enable_banking_account
def initialize(enable_banking_account)
@enable_banking_account = enable_banking_account
end
def process
unless enable_banking_account.current_account.present?
Rails.logger.info "EnableBankingAccount::Processor - No linked account for enable_banking_account #{enable_banking_account.id}, skipping processing"
return
end
Rails.logger.info "EnableBankingAccount::Processor - Processing enable_banking_account #{enable_banking_account.id} (uid #{enable_banking_account.uid})"
# Capture the reading's date before the import can cross midnight.
date = Date.current
begin
anchor_balance = process_account!
transactions_ok = process_transactions
if anchor_balance
move_pending_adjusted_anchor_forward(date)
result = enable_banking_account.current_account.set_current_balance(
anchor_balance,
date: date,
reuse_explained_anchor: transactions_ok
)
raise ProcessingError.new("Failed to set current balance: #{result.error}") unless result.success?
# 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
)
end
rescue StandardError => e
Rails.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")
enable_banking_account.update_column(:balance_verified, false) if enable_banking_account.persisted?
raise
end
# Skipped only when the batch itself raised. A run with single failed rows
# (success: false) still cleans up: both steps only touch pendings that
# already have a booked twin or are older than 8 days, and gating on
# success would stop the cleanup for good behind one row that keeps failing.
clean_up_pending_transactions unless @transactions_failed
transactions_ok
end
private
# 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")
return
end
account = enable_banking_account.current_account
balance = enable_banking_account.current_balance
# A nil current_balance means this sync's balance fetch did not succeed:
# upsert_enable_banking_snapshot! clears it and only a successful
# balance fetch repopulates it. Coercing nil to 0 here would persist a
# zero balance (and a zero current_anchor valuation) onto a healthy
# account whenever the provider has a transient failure, so leave the
# account untouched instead.
if balance.nil?
Rails.logger.warn("EnableBankingAccount::Processor - No balance available for enable_banking_account #{enable_banking_account.id} (balance fetch failed or not yet run), skipping account update")
return
end
available_credit = nil
skip_balance_update = false
# For liability accounts, ensure balance sign is correct.
# For CreditCards, we expect the main balance to reflect the absolute outstanding debt
# rather than available credit, to ensure net worth calculations handle the liability accurately.
# Any available credit metrics (from limits) are instead stored safely as metadata on the Accountable.
# Loans and CreditCards must always represent their outstanding balance as an absolute
# positive debt amount, regardless of the API's reported sign, to ensure the BalanceSheet
# calculates net worth accurately.
if account.accountable_type == "Loan" || account.accountable_type == "CreditCard"
# Standardize the raw balance to an absolute positive debt
balance = balance.abs
if account.accountable_type == "CreditCard"
balance, available_credit, skip_balance_update = interpret_credit_card_balance(account, balance)
end
end
currency = parse_currency(enable_banking_account.currency) || account.currency || "EUR"
# Wrap both writes in a transaction so a failure on either rolls back both.
ActiveRecord::Base.transaction do
if account.accountable.present? && account.accountable.respond_to?(:available_credit=)
account.accountable.update!(available_credit: available_credit)
end
if skip_balance_update
account.update!(currency: currency)
else
account.update!(currency: currency, cash_balance: balance)
end
end
balance unless skip_balance_update
end
# Interprets the reported credit card balance based on the
# treat_balance_as_available_credit flag.
# Returns [balance, available_credit, skip_balance_update].
def interpret_credit_card_balance(account, reported_balance)
if enable_banking_account.treat_balance_as_available_credit?
# In this mode the accountable's available_credit field holds the credit
# limit: the API-provided one, or a user-entered value when the API
# omits it. Writing the limit back (never the reported balance) keeps
# the field stable across syncs so a manual limit is never clobbered.
credit_limit = positive_credit_limit(enable_banking_account.credit_limit) ||
positive_credit_limit(account.accountable&.available_credit)
unless account.accountable.present?
capture_debug_log("CreditCard accountable missing for account", account)
end
if credit_limit.present?
# The API returns the available credit as the current balance, so the
# outstanding debt is derived from the credit limit.
# Use .max(0) to prevent synthetic debt on overpaid cards.
outstanding_debt = CreditCard.debt_from_available_credit(
credit_limit: credit_limit, available_credit: reported_balance, clamp_overpayment: true
)
[ outstanding_debt, credit_limit, false ]
else
# No credit limit from the API or the card's available credit field.
# The reported balance is available credit, so the outstanding debt is
# unknown. Keep the existing account balance instead of recording
# available credit as debt.
capture_debug_log("Cannot compute debt from available credit because no credit limit is set (API or manual)", account)
[ nil, nil, true ]
end
else
# Default behavior: API returns outstanding debt
provider_credit_limit = positive_credit_limit(enable_banking_account.credit_limit)
available_credit = if provider_credit_limit
[ provider_credit_limit - reported_balance, 0 ].max
else
# In this mode available_credit is the actual remaining credit, not a
# limit, so zero is valid and must be preserved intentionally.
account.accountable&.available_credit
end
[ reported_balance, available_credit, false ]
end
end
# Credit limits must be positive. Non-positive provider or manual values
# mean that no usable limit is known.
def positive_credit_limit(value)
value if value&.positive?
end
def capture_debug_log(message, account)
DebugLogEntry.capture(
category: "sync",
level: "warn",
message: message,
source: "EnableBankingAccount::Processor",
provider_key: "enable_banking",
account: account,
account_provider: account.account_providers.find_by(provider_type: "EnableBankingAccount"),
metadata: {
enable_banking_account_id: enable_banking_account.id,
enable_banking_item_id: enable_banking_account.enable_banking_item_id
}
)
end
def process_transactions
EnableBankingAccount::Transactions::Processor.new(enable_banking_account).process[:success]
rescue => e
@transactions_failed = true
report_exception(e, "transactions")
false
end
# Same safety net SimpleFIN runs after each import: a pending entry the import
# could not claim unambiguously is excluded once its booked twin shows up, and
# a pending that never booked within 8 days is excluded. The latter is marked,
# because some ASPSPs keep the same id when a pending books: the import then
# re-activates the entry instead of leaving it excluded and pending.
def clean_up_pending_transactions
account = enable_banking_account.current_account
Entry.reconcile_pending_duplicates(account: account)
Entry.auto_exclude_stale_pending(account: account, mark: true)
rescue => e
Rails.logger.warn("EnableBankingAccount::Processor - pending cleanup failed for account #{account&.id}: #{e.class} - #{e.message}")
capture_debug_log("Pending transaction cleanup failed: #{e.class} - #{e.message}", account) if account
report_exception(e, "pending_cleanup")
end
def report_exception(error, context)
Sentry.capture_exception(error) do |scope|
scope.set_tags(
enable_banking_account_id: enable_banking_account.id,
context: context
)
end
end
end