Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(balance): stop freezing mid-day provider readings as waypoints (#3519)

Guillermo Tomás Fernández Martína963ca694d86
diff --git a/.env.example b/.env.example
index d75a91c2ff..ebf44a330e 100644
--- a/.env.example
+++ b/.env.example
@@ -155,6 +155,12 @@ SECURITIES_PROVIDER=yahoo_finance
# MARKET_DATA_SYNC_TIME=22:00
# MARKET_DATA_SYNC_TIMEZONE=UTC
+# Optional: linked-account balance anchoring. When enabled, a stale provider
+# balance anchor that the sync's imported transactions explain is moved forward
+# instead of being kept as a reconciliation waypoint. Default off.
+# See docs/hosting/balance-anchors.md for rollout and rollback behavior.
+# BALANCE_REUSE_EXPLAINED_ANCHOR=1
+
# Brandfetch to grab logos for banks and merchants
BRAND_FETCH_CLIENT_ID=
diff --git a/.env.local.example b/.env.local.example
index 9f1084e26a..0cca79bb3f 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -27,6 +27,13 @@ LUNCHFLOW_DEBUG_RAW=false
# LUNCHFLOW_INCLUDE_PENDING: when truthy, adds `include_pending=true` to Lunchflow transaction fetch requests
LUNCHFLOW_INCLUDE_PENDING=false
+# Linked-account balance anchoring (default-off)
+# BALANCE_REUSE_EXPLAINED_ANCHOR: when truthy, a linked account's previous bank-reported
+# balance anchor is carried forward instead of being kept as a "Manual balance update"
+# reconciliation, whenever the transactions imported in the same sync already explain the
+# move to the newly reported balance
+BALANCE_REUSE_EXPLAINED_ANCHOR=false
+
# Controls onboarding flow (valid: open, closed, invite_only)
ONBOARDING_STATE=open
diff --git a/.env.test.example b/.env.test.example
index 9ae8da9161..2555fc11f0 100644
--- a/.env.test.example
+++ b/.env.test.example
@@ -27,6 +27,13 @@ LUNCHFLOW_DEBUG_RAW=false
# LUNCHFLOW_INCLUDE_PENDING: when truthy, adds `include_pending=true` to Lunchflow transaction fetch requests
LUNCHFLOW_INCLUDE_PENDING=false
+# Linked-account balance anchoring (default-off)
+# BALANCE_REUSE_EXPLAINED_ANCHOR: when truthy, a linked account's previous bank-reported
+# balance anchor is carried forward instead of being kept as a "Manual balance update"
+# reconciliation, whenever the transactions imported in the same sync already explain the
+# move to the newly reported balance
+BALANCE_REUSE_EXPLAINED_ANCHOR=false
+
# Controls onboarding flow (valid: open, closed, invite_only)
ONBOARDING_STATE=open
diff --git a/app/models/account/anchorable.rb b/app/models/account/anchorable.rb
index ac288970ae..66cad9eb39 100644
--- a/app/models/account/anchorable.rb
+++ b/app/models/account/anchorable.rb
@@ -70,8 +70,14 @@ module Account::Anchorable
# as of a statement rather than of this moment; it defaults to today.
# Pass schedule_sync: false when the caller schedules the account sync
# itself, such as a provider sync that syncs its accounts afterwards.
- def set_current_balance(balance, date: nil, schedule_sync: true)
- result = current_balance_manager.set_current_balance(balance, date: date)
+ # Pass reuse_explained_anchor: false when the import was partial: the reading
+ # is still recorded, but the ledger is not trusted to judge the old anchor.
+ def set_current_balance(balance, date: nil, schedule_sync: true, reuse_explained_anchor: true)
+ result = current_balance_manager.set_current_balance(
+ balance,
+ date: date,
+ reuse_explained_anchor: reuse_explained_anchor
+ )
sync_later if schedule_sync && result.success?
result
end
diff --git a/app/models/account/current_balance_manager.rb b/app/models/account/current_balance_manager.rb
index b25c59d65b..0d106efa14 100644
--- a/app/models/account/current_balance_manager.rb
+++ b/app/models/account/current_balance_manager.rb
@@ -37,9 +37,13 @@ class Account::CurrentBalanceManager
# as of a statement rather than of this moment. It only applies to a linked
# account: a manual one has no statement, and its strategies reconcile against
# today by design.
- def set_current_balance(balance, date: nil)
+ def set_current_balance(balance, date: nil, reuse_explained_anchor: true)
if account.linked?
- set_current_balance_for_linked_account(balance, date || Date.current)
+ set_current_balance_for_linked_account(
+ balance,
+ date || Date.current,
+ reuse_explained_anchor: reuse_explained_anchor
+ )
else
result = set_current_balance_for_manual_account(balance)
@@ -98,12 +102,12 @@ class Account::CurrentBalanceManager
# Linked accounts manage "current balance" via the special `current_anchor` valuation.
# This is NOT a user-facing feature, and is primarily used in "processors" while syncing
- # linked account data (e.g. via Plaid)
+ # linked account data (e.g. via Plaid).
#
- # Before overwriting a stale (previous-day) current_anchor, we convert it to a
- # reconciliation valuation. This preserves the API-reported balance as a historical
- # waypoint that the ReverseCalculator uses for more accurate balance history.
- def set_current_balance_for_linked_account(balance, date)
+ # A stale anchor the imported ledger explains moves forward in place. Otherwise it is
+ # preserved as a reconciliation waypoint (#1492, #1484). Gated on
+ # BALANCE_REUSE_EXPLAINED_ANCHOR; when off, every stale anchor is preserved.
+ def set_current_balance_for_linked_account(balance, date, reuse_explained_anchor: true)
changes_made = false
error = nil
historical = false
@@ -124,13 +128,15 @@ class Account::CurrentBalanceManager
error = result.error
historical = true
else
- # Only a statement that moves the balance forward leaves the previous
- # anchor behind as a reconciliation. One carrying the anchor's own date
- # is that same anchor restated, so it is updated rather than duplicated.
- preserve_anchor_as_reconciliation_if_stale(date) if current_anchor_valuation
+ anchor = current_anchor_valuation
+
+ if anchor && anchor.entry.date < date &&
+ (!reuse_explained_anchor || !ledger_explains?(anchor.entry, balance, date))
+ preserve_anchor_as_reconciliation_if_stale(date)
+ anchor = nil
+ end
- # Re-check: the memoized value was cleared if the anchor was converted
- if current_anchor_valuation
+ if anchor
changes_made = update_current_anchor(balance, date)
else
create_current_anchor(balance, date)
@@ -159,8 +165,11 @@ class Account::CurrentBalanceManager
Result.new(success?: result.success?, changes_made?: result.success?, error: result.error_message)
end
+ # Legacy data can still carry more than one anchor row, and the query has no ORDER BY,
+ # so pick the newest deterministically. Ids are random UUIDs: a last-resort tiebreak only.
def current_anchor_valuation
- @current_anchor_valuation ||= account.valuations.current_anchor.includes(:entry).first
+ @current_anchor_valuation ||=
+ account.valuations.current_anchor.includes(:entry).max_by { |v| [ v.entry.date, v.entry.created_at, v.entry.id ] }
end
# If the existing current_anchor is from a previous day, convert it to a
@@ -182,6 +191,37 @@ class Account::CurrentBalanceManager
@current_anchor_valuation = nil
end
+ # True when the imported transactions and trades account for the entire move
+ # between the standing anchor and the new reading. Only meaningful for :cash.
+ def ledger_explains?(older_entry, new_balance, date)
+ return false unless Rails.configuration.x.balance.reuse_explained_anchor
+ return false unless account.balance_type == :cash
+ return false unless older_entry.currency == account.currency
+
+ # Ignore entries the anchor already included: its own timestamp is the watermark.
+ # A split child inherits its parent's timestamp; the parent was the flow the anchor
+ # could have seen, and the child rows are created later by the split.
+ flows = account.entries
+ .excluding_pending
+ .excluding_split_parents
+ .where(date: older_entry.date..date)
+ .where.not(entryable_type: "Valuation")
+ .where(
+ "entries.date > :anchor_date OR " \
+ "COALESCE((SELECT pe.created_at FROM entries pe WHERE pe.id = entries.parent_entry_id), entries.created_at) > :anchor_written_at",
+ anchor_date: older_entry.date, anchor_written_at: older_entry.updated_at
+ )
+ .pluck(:currency, :amount)
+
+ return false unless flows.all? { |currency, _| currency == account.currency }
+
+ net = flows.sum { |_, amount| amount }
+ expected = older_entry.amount + (account.asset? ? -net : net)
+ tolerance = BigDecimal(Money::Currency.new(account.currency).step.to_s)
+
+ (expected - new_balance).abs <= tolerance
+ end
+
def create_current_anchor(balance, date)
account.entries.create!(
date: date,
diff --git a/app/models/coinstats_account/processor.rb b/app/models/coinstats_account/processor.rb
index c607163155..c7db612643 100644
--- a/app/models/coinstats_account/processor.rb
+++ b/app/models/coinstats_account/processor.rb
@@ -20,6 +20,9 @@ class CoinstatsAccount::Processor
Rails.logger.info "CoinstatsAccount::Processor - Processing coinstats_account #{coinstats_account.id}"
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
begin
process_holdings
rescue StandardError => e
@@ -27,8 +30,10 @@ class CoinstatsAccount::Processor
report_exception(e, "holdings")
end
+ anchor_balance = nil
+
begin
- process_account!
+ anchor_balance = process_account!
rescue StandardError => e
Rails.logger.error "CoinstatsAccount::Processor - Failed to process account #{coinstats_account.id}: #{e.message}"
Rails.logger.error "Backtrace: #{e.backtrace.join("\n")}"
@@ -37,6 +42,10 @@ class CoinstatsAccount::Processor
end
process_transactions
+
+ # Anchor the reported balance AFTER importing, so the previous reading can be judged
+ # against a complete ledger. See Account::CurrentBalanceManager.
+ coinstats_account.current_account.set_current_balance(anchor_balance, date: date) if anchor_balance
end
private
@@ -58,7 +67,8 @@ class CoinstatsAccount::Processor
currency: currency
)
- account.set_current_balance(balance)
+ # Returned to `process`, which anchors it once transactions are in.
+ balance
end
# Delegates transaction processing to the specialized processor.
diff --git a/app/models/enable_banking_account/processor.rb b/app/models/enable_banking_account/processor.rb
index ab7add31a6..2d575e6138 100644
--- a/app/models/enable_banking_account/processor.rb
+++ b/app/models/enable_banking_account/processor.rb
@@ -16,18 +16,30 @@ class EnableBankingAccount::Processor
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
- process_account!
+ anchor_balance = process_account!
+ transactions_ok = process_transactions
+
+ if anchor_balance
+ 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?
+
+ enable_banking_account.update!(balance_verified: enable_banking_account.balance_evidence_verified?)
+ 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")
- # 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?
raise
end
-
- process_transactions
end
private
@@ -83,22 +95,10 @@ class EnableBankingAccount::Processor
account.update!(currency: currency)
else
account.update!(currency: currency, cash_balance: balance)
-
- # Use set_current_balance to create a current_anchor valuation entry.
- # This enables Balance::ReverseCalculator, which works backward from the
- # 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?)
end
end
- # TODO: pass explicit window_start_date to sync_later to avoid full history recalculation on every sync
- # Currently relies on set_current_balance's implicit sync trigger; window params would require refactor
+ balance unless skip_balance_update
end
# Interprets the reported credit card balance based on the
@@ -173,9 +173,10 @@ class EnableBankingAccount::Processor
end
def process_transactions
- EnableBankingAccount::Transactions::Processor.new(enable_banking_account).process
+ EnableBankingAccount::Transactions::Processor.new(enable_banking_account).process[:success]
rescue => e
report_exception(e, "transactions")
+ false
end
def report_exception(error, context)
diff --git a/app/models/ibkr_account/processor.rb b/app/models/ibkr_account/processor.rb
index 4932ad1c51..4b5fefe72c 100644
--- a/app/models/ibkr_account/processor.rb
+++ b/app/models/ibkr_account/processor.rb
@@ -8,9 +8,28 @@ class IbkrAccount::Processor
def process
return unless account.present?
- update_account_balance!
- IbkrAccount::HoldingsProcessor.new(ibkr_account).process
- IbkrAccount::ActivitiesProcessor.new(ibkr_account).process
+ total_balance = ibkr_account.current_balance || ibkr_account.cash_balance || 0
+ cash_balance = ibkr_account.cash_balance || 0
+ date = balance_date
+
+ holdings_ok = process_holdings
+ activities_ok = process_activities
+
+ if holdings_ok && activities_ok
+ update_account_balance_and_anchor!(total_balance: total_balance, cash_balance: cash_balance, date: date)
+ else
+ DebugLogEntry.capture(
+ category: "provider_sync_error",
+ level: "error",
+ message: "Skipped IBKR anchor: holdings_ok=#{holdings_ok}, activities_ok=#{activities_ok}",
+ source: self.class.name,
+ provider_key: "ibkr",
+ account_provider: ibkr_account.account_provider,
+ family: ibkr_account.ibkr_item&.family,
+ metadata: { report_date: ibkr_account.report_date&.to_s, balance_date: date.to_s }
+ )
+ end
+
repair_default_opening_anchor!
move_opening_anchor_before_entries!
@@ -23,9 +42,23 @@ class IbkrAccount::Processor
@account ||= ibkr_account.current_account
end
- def update_account_balance!
- total_balance = ibkr_account.current_balance || ibkr_account.cash_balance || 0
- cash_balance = ibkr_account.cash_balance || 0
+ def process_holdings
+ IbkrAccount::HoldingsProcessor.new(ibkr_account).process
+ true
+ rescue => e
+ report_exception(e, "holdings")
+ false
+ end
+
+ def process_activities
+ IbkrAccount::ActivitiesProcessor.new(ibkr_account).process
+ true
+ rescue => e
+ report_exception(e, "activities")
+ false
+ end
+
+ def update_account_balance_and_anchor!(total_balance:, cash_balance:, date:)
result = nil
# One lock across the whole of it. Which statement the account follows is
@@ -42,7 +75,7 @@ class IbkrAccount::Processor
# an older one leaves the balance where it is, and the cached figures
# must keep the denomination they were written in. Rolled back below
# with everything else if the write fails.
- if ibkr_account.currency != account.currency && !statement_behind_anchor?(manager)
+ if ibkr_account.currency != account.currency && !statement_behind_anchor?(manager, date)
account.update!(currency: ibkr_account.currency)
end
@@ -52,7 +85,7 @@ class IbkrAccount::Processor
# prices, and the cash plug absorbs the difference -- a phantom balance
# the size of whatever the holdings moved that day, on every day of the
# account's history.
- result = manager.set_current_balance(total_balance, date: balance_date)
+ result = manager.set_current_balance(total_balance, date: date)
# The manager rescues and reports failure through its result, and its
# own lock joined this transaction rather than opening one -- so what
@@ -81,15 +114,15 @@ class IbkrAccount::Processor
provider_key: "ibkr",
account_provider: ibkr_account.account_provider,
family: ibkr_account.ibkr_item&.family,
- metadata: { report_date: ibkr_account.report_date&.to_s, balance_date: balance_date.to_s }
+ metadata: { report_date: ibkr_account.report_date&.to_s, balance_date: date.to_s }
)
end
result
end
- def statement_behind_anchor?(manager)
- manager.has_current_anchor? && manager.current_date > balance_date
+ def statement_behind_anchor?(manager, date)
+ manager.has_current_anchor? && manager.current_date > date
end
def balance_date
@@ -140,4 +173,13 @@ class IbkrAccount::Processor
Sentry.capture_message(result.error)
end
end
+
+ def report_exception(error, context)
+ Sentry.capture_exception(error) do |scope|
+ scope.set_tags(
+ ibkr_account_id: ibkr_account.id,
+ context: context
+ )
+ end
+ end
end
diff --git a/app/models/indexa_capital_account/activities_processor.rb b/app/models/indexa_capital_account/activities_processor.rb
index 082467fc23..e4c8bf52cf 100644
--- a/app/models/indexa_capital_account/activities_processor.rb
+++ b/app/models/indexa_capital_account/activities_processor.rb
@@ -39,21 +39,23 @@ class IndexaCapitalAccount::ActivitiesProcessor
def process
activities_data = @indexa_capital_account.raw_activities_payload
- return { trades: 0, transactions: 0 } if activities_data.blank?
+ return { trades: 0, transactions: 0, failed: 0 } if activities_data.blank?
Rails.logger.info "IndexaCapitalAccount::ActivitiesProcessor - Processing #{activities_data.size} activities"
@trades_count = 0
@transactions_count = 0
+ @failed_count = 0
activities_data.each do |activity_data|
process_activity(activity_data.with_indifferent_access)
rescue => e
+ @failed_count += 1
Rails.logger.error "IndexaCapitalAccount::ActivitiesProcessor - Failed to process activity: #{e.message}"
Rails.logger.error e.backtrace.first(5).join("\n") if e.backtrace
end
- { trades: @trades_count, transactions: @transactions_count }
+ { trades: @trades_count, transactions: @transactions_count, failed: @failed_count }
end
private
diff --git a/app/models/indexa_capital_account/processor.rb b/app/models/indexa_capital_account/processor.rb
index 8a5d951864..d279f6fc24 100644
--- a/app/models/indexa_capital_account/processor.rb
+++ b/app/models/indexa_capital_account/processor.rb
@@ -15,8 +15,10 @@ class IndexaCapitalAccount::Processor
Rails.logger.info "IndexaCapitalAccount::Processor - Processing account #{indexa_capital_account.id} -> Sure account #{account.id}"
- # Update account balance FIRST (before processing transactions/holdings/activities)
- update_account_balance(account)
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
+ anchor_balance = update_account_balance(account)
# Process holdings
holdings_count = indexa_capital_account.raw_holdings_payload&.size || 0
@@ -33,13 +35,23 @@ class IndexaCapitalAccount::Processor
activities_count = indexa_capital_account.raw_activities_payload&.size || 0
Rails.logger.info "IndexaCapitalAccount::Processor - Activities payload has #{activities_count} items"
+ activities_ok = true
if indexa_capital_account.raw_activities_payload.present?
Rails.logger.info "IndexaCapitalAccount::Processor - Processing activities..."
- IndexaCapitalAccount::ActivitiesProcessor.new(indexa_capital_account).process
+ activities = IndexaCapitalAccount::ActivitiesProcessor.new(indexa_capital_account).process
+ activities_ok = activities[:failed].zero?
else
Rails.logger.warn "IndexaCapitalAccount::Processor - No activities payload to process"
end
+ if anchor_balance
+ account.set_current_balance(
+ anchor_balance,
+ date: date,
+ reuse_explained_anchor: activities_ok
+ )
+ end
+
# Trigger immediate UI refresh so entries appear in the activity feed
account.broadcast_sync_complete
Rails.logger.info "IndexaCapitalAccount::Processor - Broadcast sync complete for account #{account.id}"
@@ -64,9 +76,7 @@ class IndexaCapitalAccount::Processor
)
account.save!
- # Create or update the current balance anchor valuation for linked accounts
- # This is critical for reverse sync to work correctly
- account.set_current_balance(total_balance)
+ total_balance
end
def calculate_total_balance
diff --git a/app/models/plaid_account/investments/holdings_processor.rb b/app/models/plaid_account/investments/holdings_processor.rb
index 44b967ea23..29ad89510b 100644
--- a/app/models/plaid_account/investments/holdings_processor.rb
+++ b/app/models/plaid_account/investments/holdings_processor.rb
@@ -1,7 +1,8 @@
class PlaidAccount::Investments::HoldingsProcessor
- def initialize(plaid_account, security_resolver:)
+ def initialize(plaid_account, security_resolver:, currency: nil)
@plaid_account = plaid_account
@security_resolver = security_resolver
+ @currency = currency
end
def process
@@ -29,7 +30,7 @@ class PlaidAccount::Investments::HoldingsProcessor
security: security,
quantity: quantity_bd,
amount: amount_bd,
- currency: plaid_holding["iso_currency_code"] || account.currency,
+ currency: plaid_holding["iso_currency_code"] || @currency || account.currency,
date: holding_date,
price: price_bd,
account_provider_id: plaid_account.account_provider&.id,
diff --git a/app/models/plaid_account/processor.rb b/app/models/plaid_account/processor.rb
index b17dccd9c0..37bd4cf3ce 100644
--- a/app/models/plaid_account/processor.rb
+++ b/app/models/plaid_account/processor.rb
@@ -17,10 +17,16 @@ class PlaidAccount::Processor
# Processing the account is the first step and if it fails, we halt the entire processor
# Each subsequent step can fail independently, but we continue processing the rest of the steps
def process
- process_account!
- process_transactions
- process_investments
+ account, balance_info = process_account!
+ transactions_ok = process_transactions
+ investments_ok = process_investments
process_liabilities
+
+ anchor_account!(
+ account,
+ balance_info,
+ reuse_explained_anchor: transactions_ok && investments_ok
+ )
end
private
@@ -105,51 +111,58 @@ class PlaidAccount::Processor
)
end
- # Create or update the current balance anchor valuation for event-sourced ledger
- # Note: This is a partial implementation. In the future, we'll introduce HoldingValuation
- # to properly track the holdings vs. cash breakdown, but for now we're only tracking
- # the total balance in the current anchor. The cash_balance field on the account model
- # is still being used for the breakdown.
- #
- # One lock across the whole of it, as in IbkrAccount::Processor: which
- # snapshot the account follows is decided by the anchor's date, and a
- # sync running beside this one can move that anchor between any two of
- # these writes. The currency, the anchor and the cash split are settled
- # together, and follow the same snapshot. The manager is called directly;
- # the Anchorable wrapper queues the sync, which belongs after the lock.
- result = nil
- account.with_lock do
- manager = Account::CurrentBalanceManager.new(account)
- behind_anchor = manager.has_current_anchor? && manager.current_date > balance_date
-
- # A snapshot dated behind the anchor is a correction to a day gone
- # by: the cached balance and cash describe now and stay as they are,
- # in the denomination they were written in.
- if !behind_anchor && account.currency != plaid_account.currency
- account.update!(currency: plaid_account.currency)
- end
-
- result = manager.set_current_balance(balance, date: balance_date)
- raise BalanceError, "Failed to set current balance: #{result.error}" unless result.success?
-
- account.update!(cash_balance: cash_balance) unless result.historical?
+ [ account, { balance: balance, cash_balance: cash_balance, balance_date: balance_date } ]
+ end
+ end
+
+ def anchor_account!(account, balance_info, reuse_explained_anchor:)
+ balance = balance_info[:balance]
+ cash_balance = balance_info[:cash_balance]
+ balance_date = balance_info[:balance_date]
+
+ account.with_lock do
+ manager = Account::CurrentBalanceManager.new(account)
+ behind_anchor = manager.has_current_anchor? && manager.current_date > balance_date
+
+ if !behind_anchor && account.currency != plaid_account.currency
+ account.update!(currency: plaid_account.currency)
end
- account.sync_later
+ result = manager.set_current_balance(
+ balance,
+ date: balance_date,
+ reuse_explained_anchor: reuse_explained_anchor
+ )
+ raise BalanceError, "Failed to set current balance: #{result.error}" unless result.success?
+
+ account.update!(cash_balance: cash_balance) unless result.historical?
end
+
+ account.sync_later
+ rescue BalanceError => e
+ report_exception(e)
+ raise
end
def process_transactions
PlaidAccount::Transactions::Processor.new(plaid_account).process
+ true
rescue => e
report_exception(e)
+ false
end
def process_investments
PlaidAccount::Investments::TransactionsProcessor.new(plaid_account, security_resolver: security_resolver).process
- PlaidAccount::Investments::HoldingsProcessor.new(plaid_account, security_resolver: security_resolver).process
+ PlaidAccount::Investments::HoldingsProcessor.new(
+ plaid_account,
+ security_resolver: security_resolver,
+ currency: plaid_account.currency
+ ).process
+ true
rescue => e
report_exception(e)
+ false
end
def process_liabilities
diff --git a/app/models/questrade_account/activities_processor.rb b/app/models/questrade_account/activities_processor.rb
index edddc3b342..56f50ff9cf 100644
--- a/app/models/questrade_account/activities_processor.rb
+++ b/app/models/questrade_account/activities_processor.rb
@@ -32,19 +32,21 @@ class QuestradeAccount::ActivitiesProcessor
end
def process
- return { trades: 0, transactions: 0 } unless account.present?
+ return { trades: 0, transactions: 0, failed: 0 } unless account.present?
@trades_count = 0
@transactions_count = 0
+ @failed_count = 0
activities.each do |raw|
process_activity(raw.with_indifferent_access)
rescue => e
+ @failed_count += 1
Rails.logger.error "QuestradeAccount::ActivitiesProcessor - Failed to process activity: #{e.message}"
Rails.logger.error e.backtrace.first(5).join("\n") if e.backtrace
end
- { trades: @trades_count, transactions: @transactions_count }
+ { trades: @trades_count, transactions: @transactions_count, failed: @failed_count }
end
private
diff --git a/app/models/questrade_account/processor.rb b/app/models/questrade_account/processor.rb
index e1526f1a68..bdcda658b3 100644
--- a/app/models/questrade_account/processor.rb
+++ b/app/models/questrade_account/processor.rb
@@ -15,16 +15,29 @@ class QuestradeAccount::Processor
Rails.logger.info "QuestradeAccount::Processor - Processing account #{questrade_account.id} -> Sure account #{account.id}"
- # Anchor the account at its reported total (cash + holdings) and store the
- # primary-currency cash. Non-primary cash is surfaced as holdings below.
- update_account_balance(account)
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
+ # Store the reported total (cash + holdings) and the primary-currency cash.
+ # Non-primary cash is surfaced as holdings below.
+ anchor_balance = update_account_balance(account)
if questrade_account.raw_holdings_payload.present? || questrade_account.non_primary_cash_entries.any?
QuestradeAccount::HoldingsProcessor.new(questrade_account).process
end
+ activities_ok = true
if questrade_account.raw_activities_payload.present?
- QuestradeAccount::ActivitiesProcessor.new(questrade_account).process
+ activities = QuestradeAccount::ActivitiesProcessor.new(questrade_account).process
+ activities_ok = activities[:failed].zero?
+ end
+
+ if anchor_balance
+ account.set_current_balance(
+ anchor_balance,
+ date: date,
+ reuse_explained_anchor: activities_ok
+ )
end
account.broadcast_sync_complete
@@ -50,8 +63,6 @@ class QuestradeAccount::Processor
)
account.save!
- # Current-balance anchor = the reported total (cash + holdings). The value
- # is composed from the holdings + per-currency cash, not a made-up figure.
- account.set_current_balance(total)
+ total
end
end
diff --git a/app/models/redbark_account/processor.rb b/app/models/redbark_account/processor.rb
index 14af0c2f54..9b2865b6b2 100644
--- a/app/models/redbark_account/processor.rb
+++ b/app/models/redbark_account/processor.rb
@@ -18,20 +18,32 @@ class RedbarkAccount::Processor
Rails.logger.info "RedbarkAccount::Processor - Processing account #{redbark_account.id} -> Sure account #{account.id}"
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
# Update account balance FIRST (before processing transactions/holdings/activities)
- update_account_balance(account)
+ anchor_balance = update_account_balance(account)
# Process transactions
transactions_count = redbark_account.raw_transactions_payload&.size || 0
Rails.logger.info "RedbarkAccount::Processor - Transactions payload has #{transactions_count} items"
+ transactions_ok = true
if redbark_account.raw_transactions_payload.present?
Rails.logger.info "RedbarkAccount::Processor - Processing transactions..."
- RedbarkAccount::Transactions::Processor.new(redbark_account).process
+ transactions_ok = RedbarkAccount::Transactions::Processor.new(redbark_account).process[:success]
else
Rails.logger.warn "RedbarkAccount::Processor - No transactions payload to process"
end
+ if anchor_balance
+ account.set_current_balance(
+ anchor_balance,
+ date: date,
+ reuse_explained_anchor: transactions_ok
+ )
+ end
+
# A loan's rate, read from what the bank reported. After transactions, so a
# failure here cannot cost the user their entries; a raise would be caught
# by RedbarkItem#process_accounts and logged per account.
@@ -81,8 +93,6 @@ class RedbarkAccount::Processor
)
account.save!
- # Create or update the current balance anchor valuation for linked accounts
- # This is critical for reverse sync to work correctly
- account.set_current_balance(balance)
+ balance
end
end
diff --git a/app/models/snaptrade_account/activities_processor.rb b/app/models/snaptrade_account/activities_processor.rb
index 552e0466a9..cf121be52e 100644
--- a/app/models/snaptrade_account/activities_processor.rb
+++ b/app/models/snaptrade_account/activities_processor.rb
@@ -77,16 +77,18 @@ class SnaptradeAccount::ActivitiesProcessor
def process
activities_data = @snaptrade_account.raw_activities_payload
- return { trades: 0, transactions: 0 } if activities_data.blank?
+ return { trades: 0, transactions: 0, failed: 0 } if activities_data.blank?
Rails.logger.info "SnaptradeAccount::ActivitiesProcessor - Processing #{activities_data.size} activities"
@trades_count = 0
@transactions_count = 0
+ @failed_count = 0
activities_data.each do |activity_data|
process_activity(activity_data.with_indifferent_access)
rescue => e
+ @failed_count += 1
activity = activity_data.is_a?(Hash) ? activity_data.with_indifferent_access : {}
capture_debug_log(
category: "provider_sync_error",
@@ -101,7 +103,7 @@ class SnaptradeAccount::ActivitiesProcessor
)
end
- { trades: @trades_count, transactions: @transactions_count }
+ { trades: @trades_count, transactions: @transactions_count, failed: @failed_count }
end
private
diff --git a/app/models/snaptrade_account/processor.rb b/app/models/snaptrade_account/processor.rb
index f9bddc31db..4aa0dead48 100644
--- a/app/models/snaptrade_account/processor.rb
+++ b/app/models/snaptrade_account/processor.rb
@@ -13,9 +13,10 @@ class SnaptradeAccount::Processor
Rails.logger.info "SnaptradeAccount::Processor - Processing account #{snaptrade_account.id} -> Sure account #{account.id}"
- # Update account balance FIRST (before processing holdings/activities)
- # This creates the current_anchor valuation needed for reverse sync
- update_account_balance(account)
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
+ anchor_balance = update_account_balance(account)
# Process holdings
holdings_count = snaptrade_account.raw_holdings_payload&.size || 0
@@ -29,13 +30,23 @@ class SnaptradeAccount::Processor
activities_count = snaptrade_account.raw_activities_payload&.size || 0
Rails.logger.info "SnaptradeAccount::Processor - Activities payload has #{activities_count} items"
+ activities_ok = true
if snaptrade_account.raw_activities_payload.present?
Rails.logger.info "SnaptradeAccount::Processor - Processing activities..."
- SnaptradeAccount::ActivitiesProcessor.new(snaptrade_account).process
+ activities = SnaptradeAccount::ActivitiesProcessor.new(snaptrade_account).process
+ activities_ok = activities[:failed].zero?
else
Rails.logger.warn "SnaptradeAccount::Processor - No activities payload to process"
end
+ if anchor_balance
+ account.set_current_balance(
+ anchor_balance,
+ date: date,
+ reuse_explained_anchor: activities_ok
+ )
+ end
+
# Trigger immediate UI refresh so entries appear in the activity feed
# This is critical for fresh account links where the sync complete broadcast
# might be delayed by child syncs (balance calculations)
@@ -62,9 +73,7 @@ class SnaptradeAccount::Processor
)
account.save!
- # Create or update the current balance anchor valuation for linked accounts
- # This is critical for reverse sync to work correctly
- account.set_current_balance(total_balance)
+ total_balance
end
def calculate_total_balance
diff --git a/app/models/sophtron_account/processor.rb b/app/models/sophtron_account/processor.rb
index 991fa7bb55..4b6d4d1683 100644
--- a/app/models/sophtron_account/processor.rb
+++ b/app/models/sophtron_account/processor.rb
@@ -34,8 +34,12 @@ class SophtronAccount::Processor
end
Rails.logger.info "SophtronAccount::Processor - Processing sophtron_account #{sophtron_account.id} (account #{sophtron_account.account_id})"
+
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
begin
- process_account!
+ account, balance, currency = balance_for_anchor
rescue StandardError => e
Rails.logger.error "SophtronAccount::Processor - Failed to process account #{sophtron_account.id}: #{e.message}"
Rails.logger.error "Backtrace: #{e.backtrace.join("\n")}"
@@ -43,59 +47,87 @@ class SophtronAccount::Processor
raise
end
- process_transactions
+ transactions_ok = process_transactions
+
+ begin
+ anchor_account!(account, balance, currency, date, reuse_explained_anchor: transactions_ok)
+ rescue StandardError => e
+ Rails.logger.error "SophtronAccount::Processor - Failed to anchor account #{sophtron_account.id}: #{e.message}"
+ Rails.logger.error "Backtrace: #{e.backtrace.join("\n")}"
+ report_exception(e, "account")
+ raise
+ end
end
- # Updates the linked Maybe Account's balance from Sophtron data.
- #
- # Handles sign conventions for different account types:
- # - Credit cards negate the provider balance unless a balance sign
- # override says the amount is debt or a genuine credit
- # - Loans always use inverted signs (negated)
- # - Other account types use Sophtron's native sign convention
- #
- # @return [void]
- # @raise [StandardError] if the account or its current balance anchor cannot be updated
+ # Applies the provider balance immediately. Used when the user changes the
+ # balance sign override; the sync path imports transactions before anchoring.
def process_account!
- account = sophtron_account.current_account
- if account.blank?
- Rails.logger.error("Sophtron account #{sophtron_account.id} has no associated Account")
- return
- end
+ account, balance, currency = balance_for_anchor
+ return if account.nil?
+
+ anchor_account!(account, balance, currency, Date.current, reuse_explained_anchor: true)
+ end
+
+ private
+
+ # Computes the linked Maybe Account's balance from Sophtron data.
+ #
+ # Handles sign conventions for different account types:
+ # - Credit cards negate the provider balance unless a balance sign
+ # override says the amount is debt or a genuine credit
+ # - Loans always use inverted signs (negated)
+ # - Other account types use Sophtron's native sign convention
+ #
+ # @return [Array(Account, Numeric, String), nil] account, balance and currency
+ # @raise [StandardError] if the account cannot be read
+ def balance_for_anchor
+ account = sophtron_account.current_account
+ if account.blank?
+ Rails.logger.error("Sophtron account #{sophtron_account.id} has no associated Account")
+ return
+ end
- # Update account balance from latest Sophtron data
- balance = signed_balance(account, sophtron_account.observed_balance)
+ balance = signed_balance(account, sophtron_account.observed_balance)
- # Normalize currency with fallback chain: parsed sophtron currency -> existing account currency -> USD
- currency = parse_currency(sophtron_account.currency) || account.currency || "USD"
+ # Normalize currency with fallback chain: parsed sophtron currency -> existing account currency -> USD
+ currency = parse_currency(sophtron_account.currency) || account.currency || "USD"
- # The anchor is what a later account sync reads. Write it here, without
- # queueing that sync, so the caller can schedule one sync after every
- # account has been updated.
- ActiveRecord::Base.transaction do
- account.update!(currency: currency)
- result = account.set_current_balance(balance, schedule_sync: false)
- raise StandardError, "Failed to set current balance: #{result.error}" unless result.success?
- account.update!(cash_balance: balance) unless result.historical?
+ [ account, balance, currency ]
end
- end
- private
+ # Writes the anchor only after the transaction batch has been imported, so the
+ # manager can judge the standing anchor against a complete ledger.
+ def anchor_account!(account, balance, currency, date, reuse_explained_anchor:)
+ # The anchor is what a later account sync reads. Write it here, without
+ # queueing that sync, so the caller can schedule one sync after every
+ # account has been updated.
+ ActiveRecord::Base.transaction do
+ account.update!(currency: currency)
+ result = account.set_current_balance(
+ balance,
+ date: date,
+ schedule_sync: false,
+ reuse_explained_anchor: reuse_explained_anchor
+ )
+ raise StandardError, "Failed to set current balance: #{result.error}" unless result.success?
+ account.update!(cash_balance: balance) unless result.historical?
+ end
+ end
# Processes all stored transactions for this account.
#
# Delegates to SophtronAccount::Transactions::Processor to convert
# raw transaction data into Maybe Transaction records.
#
- # @return [void]
- # @raise [StandardError] if transaction processing fails
+ # @return [Boolean] true when the batch imported without per-row failures
def process_transactions
- SophtronAccount::Transactions::Processor.new(sophtron_account).process
+ result = SophtronAccount::Transactions::Processor.new(sophtron_account).process
+ result[:success]
rescue StandardError => e
Rails.logger.error "SophtronAccount::Processor - Failed to process transactions for sophtron_account #{sophtron_account.id}: #{e.message}"
Rails.logger.error "Backtrace: #{e.backtrace.join("\n")}"
report_exception(e, "transactions")
- raise
+ false
end
# Converts a Sophtron balance into Sure's stored sign.
diff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rb
index d10a2ff38e..eb4967d1b8 100644
--- a/app/models/trade_republic_account/activities_processor.rb
+++ b/app/models/trade_republic_account/activities_processor.rb
@@ -36,10 +36,11 @@ class TradeRepublicAccount::ActivitiesProcessor
end
def process
- return { trades: 0, transactions: 0 } unless account.present?
+ return { trades: 0, transactions: 0, failed: 0 } unless account.present?
trade_count = 0
transaction_count = 0
+ @failed_count = 0
# Also before the events: a trade that moved to the Crypto account has to
# lose its portfolio counterpart before its settlement can link to a new
@@ -75,7 +76,7 @@ class TradeRepublicAccount::ActivitiesProcessor
reconcile_settlement_counterparts!
capture_incomplete_executions
- { trades: trade_count, transactions: transaction_count }
+ { trades: trade_count, transactions: transaction_count, failed: @failed_count }
end
private
@@ -225,6 +226,7 @@ class TradeRepublicAccount::ActivitiesProcessor
import_labeled_cash_movement(event, detail, external_id, date, "dividend", sign: -1)
end
rescue => e
+ @failed_count += 1
DebugLogEntry.capture(
category: "sync",
level: "error",
diff --git a/app/models/trade_republic_account/processor.rb b/app/models/trade_republic_account/processor.rb
index efb00de26b..e46aadf36f 100644
--- a/app/models/trade_republic_account/processor.rb
+++ b/app/models/trade_republic_account/processor.rb
@@ -10,10 +10,24 @@ class TradeRepublicAccount::Processor
exchange_securities = TradeRepublicAccount::SecurityPrefetcher.new(trade_republic_account).prefetch
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
ActiveRecord::Base.transaction do
- update_account_balance!
+ total_balance = update_account_balance!
TradeRepublicAccount::HoldingsProcessor.new(trade_republic_account, exchange_securities: exchange_securities).process
- TradeRepublicAccount::ActivitiesProcessor.new(trade_republic_account, exchange_securities: exchange_securities).process
+ activities = TradeRepublicAccount::ActivitiesProcessor.new(
+ trade_republic_account,
+ exchange_securities: exchange_securities
+ ).process
+
+ # TradeRepublicItem schedules account syncs after every account is processed.
+ account.set_current_balance(
+ total_balance,
+ date: date,
+ schedule_sync: false,
+ reuse_explained_anchor: activities[:failed].zero?
+ )
end
account.broadcast_sync_complete
@@ -35,9 +49,7 @@ class TradeRepublicAccount::Processor
currency: trade_republic_account.currency
)
account.save!
- # TradeRepublicItem#schedule_account_syncs syncs the account once every
- # Trade Republic account has been processed. A sync started here would
- # run before the other accounts book their settlements, and then again.
- account.set_current_balance(total_balance, schedule_sync: false)
+
+ total_balance
end
end
diff --git a/app/models/trading212_account/processor.rb b/app/models/trading212_account/processor.rb
index 54f8c6a5e8..b0227b80f8 100644
--- a/app/models/trading212_account/processor.rb
+++ b/app/models/trading212_account/processor.rb
@@ -8,10 +8,17 @@ class Trading212Account::Processor
def process
return unless account.present?
- update_account_balance!
+ # Capture the reading's date before the import can cross midnight.
+ date = Date.current
+
+ total_balance = update_account_balance!
Trading212Account::HoldingsProcessor.new(trading212_account).process
Trading212Account::ActivitiesProcessor.new(trading212_account).process
+ # Anchor the reported balance AFTER importing, so the previous reading can be judged
+ # against a complete ledger. See Account::CurrentBalanceManager.
+ account.set_current_balance(total_balance, date: date)
+
account.broadcast_sync_complete
end
@@ -31,6 +38,8 @@ class Trading212Account::Processor
currency: trading212_account.currency
)
account.save!
- account.set_current_balance(total_balance)
+
+ # Returned to `process`, which anchors it once holdings and activities are in.
+ total_balance
end
end
diff --git a/config/initializers/balance_anchor.rb b/config/initializers/balance_anchor.rb
new file mode 100644
index 0000000000..8f24ecbe94
--- /dev/null
+++ b/config/initializers/balance_anchor.rb
@@ -0,0 +1,9 @@
+# Linked-account current balance anchor runtime configuration
+Rails.application.configure do
+ # Controls whether a stale `current_anchor` is carried forward when the transactions
+ # imported in the same sync already explain the move to the newly reported balance.
+ # When false, every stale anchor is frozen as a reconciliation waypoint ("Manual
+ # balance update"), which is the historical behaviour.
+ # Default: false
+ config.x.balance.reuse_explained_anchor = ENV["BALANCE_REUSE_EXPLAINED_ANCHOR"].to_s.strip.downcase.in?(%w[1 true yes])
+end
diff --git a/docs/hosting/balance-anchors.md b/docs/hosting/balance-anchors.md
new file mode 100644
index 0000000000..c481af6591
--- /dev/null
+++ b/docs/hosting/balance-anchors.md
@@ -0,0 +1,29 @@
+# Linked-account balance anchoring
+
+`BALANCE_REUSE_EXPLAINED_ANCHOR` controls how Sure handles a linked account's stale, provider-reported balance anchor.
+
+## Default: off
+
+When the flag is unset or false, every stale anchor is kept as a reconciliation waypoint ("Manual balance update"). This preserves the pre-existing behavior.
+
+## Enabled: explained anchors move forward
+
+When the flag is truthy (`1`, `true`, or `yes`), the manager compares the stale anchor with the provider's new reading using the transactions imported in the same sync. If the imported ledger explains the move, the anchor is updated in place (amount and date). If it does not, the old anchor is preserved as a reconciliation waypoint and a new anchor is created.
+
+Only `:cash` accounts are evaluated. Investment, crypto, and other non-cash accounts keep the old behavior. Providers that update account balances directly, such as SimpleFIN and Lunchflow, are outside this path.
+
+## Rollout
+
+- The flag is off by default. Enable it deliberately per installation.
+- On the first reverse sync after enabling, materialized balance rows are recalculated and historical charts may move to corrected values.
+- Existing reconciliation rows created by prior rotations are not deleted or rewritten. Provenance is not stored, so an automatic repair cannot distinguish a sync-created waypoint from a genuine user reconciliation.
+
+## Rollback
+
+Turning the flag off restores the old preserve-every-stale-anchor behavior for future syncs. It does not restore an anchor that was overwritten while the flag was enabled. Reverting the code has the same limitation.
+
+If you need to preserve the pre-enable state, take a database backup and a baseline of daily balances before enabling the flag.
+
+## Release note
+
+> Linked-account balance anchoring is available behind `BALANCE_REUSE_EXPLAINED_ANCHOR` (default off). When enabled, provider observations explained by imported transactions are moved forward instead of being kept as daily "Manual balance update" reconciliations. Existing reconciliations are retained; there is no automatic historical repair. Enabling the flag can revise historical chart values and overwrites explained anchors irreversibly, so take a backup before enabling it.
diff --git a/docs/hosting/docker.md b/docs/hosting/docker.md
index 0140251524..5ed21f546b 100644
--- a/docs/hosting/docker.md
+++ b/docs/hosting/docker.md
@@ -65,6 +65,8 @@ To do this, you should get our .env.example as a starting point:
curl --fail --location --silent --show-error --output .env https://raw.githubusercontent.com/we-promise/sure/main/.env.example
```
+Optional linked-account balance anchoring is documented separately; see [Linked-account balance anchoring](balance-anchors.md) before enabling `BALANCE_REUSE_EXPLAINED_ANCHOR`.
+
#### Generate the app secret key
The app requires an environment variable called `SECRET_KEY_BASE` to run.
diff --git a/lib/generators/provider/family/templates/account_processor.rb.tt b/lib/generators/provider/family/templates/account_processor.rb.tt
index 80dd5f846a..6a671346b6 100644
--- a/lib/generators/provider/family/templates/account_processor.rb.tt
+++ b/lib/generators/provider/family/templates/account_processor.rb.tt
@@ -15,8 +15,7 @@ class <%= class_name %>Account::Processor
Rails.logger.info "<%= class_name %>Account::Processor - Processing account #{<%= file_name %>_account.id} -> Sure account #{account.id}"
- # Update account balance FIRST (before processing transactions/holdings/activities)
- update_account_balance(account)
+ anchor_balance = update_account_balance(account)
<% if investment_provider? -%>
# Process holdings
@@ -54,6 +53,11 @@ class <%= class_name %>Account::Processor
end
<% end -%>
+ # Anchor the reported balance AFTER importing, never before. The anchor is judged
+ # against the imported ledger, so the transactions for this sync must already be
+ # persisted when it is written. See Account::CurrentBalanceManager.
+ account.set_current_balance(anchor_balance) if anchor_balance
+
# Trigger immediate UI refresh so entries appear in the activity feed
account.broadcast_sync_complete
Rails.logger.info "<%= class_name %>Account::Processor - Broadcast sync complete for account #{account.id}"
@@ -103,9 +107,8 @@ class <%= class_name %>Account::Processor
account.save!
<% end -%>
- # Create or update the current balance anchor valuation for linked accounts
- # This is critical for reverse sync to work correctly
- account.set_current_balance(<%= investment_provider? ? "total_balance" : "balance" %>)
+ # Returned to `process`, which anchors it once the import is done.
+ <%= investment_provider? ? "total_balance" : "balance" %>
end
<% if investment_provider? -%>
diff --git a/test/models/account/anchor_behavior_scenarios_test.rb b/test/models/account/anchor_behavior_scenarios_test.rb
new file mode 100644
index 0000000000..dc55aeccc3
--- /dev/null
+++ b/test/models/account/anchor_behavior_scenarios_test.rb
@@ -0,0 +1,306 @@
+require "test_helper"
+
+# Acceptance scenarios for mid-day provider readings. Each drives a real provider sync and
+# asserts on materialized balances, so the processor's anchor ordering is exercised too.
+class AnchorBehaviorScenariosTest < ActiveSupport::TestCase
+ SYNC_TIME_OF_DAY = "02:22"
+
+ setup do
+ @day_one = Date.current - 7.days
+ @plaid_account = plaid_accounts(:one)
+
+ assert_equal 0, accounts(:connected).entries.count
+
+ # The reuse of an explained anchor is gated on BALANCE_REUSE_EXPLAINED_ANCHOR (default off).
+ Rails.configuration.x.balance.stubs(:reuse_explained_anchor).returns(true)
+ end
+
+ # A mid-day reading must not become that day's closing waypoint.
+ test "a mid-day reading is not frozen as that day's closing balance" do
+ account = seed_opening_balance(1000)
+
+ # Day one, 02:22: provider reports 1000. Nothing has posted yet.
+ provider_sync!(@plaid_account, on: day(1), reading: 1000)
+
+ # Day two, 02:22: the 400 that posted after yesterday's reading arrives in this batch,
+ # dated to day one (normal for overnight PSD2 / Enable Banking batches), and the
+ # provider now reports 600.
+ provider_sync!(
+ @plaid_account,
+ on: day(2),
+ reading: 600,
+ imports: [ { date: day(1), amount: 400, name: "Card payment" } ]
+ )
+
+ materialize!(account)
+
+ day_one_row = balance_row(account, day(1))
+ assert_equal 600, day_one_row.balance,
+ "day one's CLOSING balance must be its true close (600), not the mid-day reading (1000)"
+ assert_equal 1000, day_one_row.start_cash_balance,
+ "day one opened at 1000 and closed at 600 after the 400 posted"
+
+ assert_equal 1000, balance_on(account, day(0)),
+ "the day before the reading must not be inflated by the 400 that posted after it"
+ assert_not_equal 1400, balance_on(account, day(0))
+ assert_equal 1000, balance_on(account, day(-2))
+
+ provider_sync!(@plaid_account, on: day(3), reading: 600)
+
+ materialize!(account)
+
+ assert_equal 600, balance_on(account, day(1))
+ assert_equal 1000, balance_on(account, day(0))
+ assert_equal 1000, balance_on(account, day(-2))
+ assert_equal 600, balance_on(account, day(3)), "today's balance is still the provider's"
+ end
+
+ # An unexplained move must leave a provider waypoint behind (#1492, #1484).
+ test "history stays grounded at the provider's reading when the ledger cannot explain a move" do
+ account = seed_opening_balance(1000)
+
+ provider_sync!(@plaid_account, on: day(1), reading: 1000)
+
+ provider_sync!(@plaid_account, on: day(2), reading: 2000)
+ provider_sync!(@plaid_account, on: day(3), reading: 2000)
+
+ materialize!(account)
+
+ assert_equal 2000, balance_on(account, day(3)), "today is still the provider's reading"
+
+ assert_equal 1000, balance_on(account, day(0)),
+ "the unexplained +1000 must not propagate to days before the reading that proves it"
+ assert_not_equal 2000, balance_on(account, day(0))
+ assert_equal 1000, balance_on(account, day(-2)),
+ "drift must stay bounded all the way back to the opening balance"
+ end
+
+ # Repeated explained syncs must not accumulate visible valuation rows.
+ test "ordinary syncs whose ledger explains every move leave no valuation clutter behind" do
+ account = nil
+
+ # Each day's 100 posts after that day's 02:22 reading, so it arrives dated to the
+ # previous day in the next day's batch - and the reading always trails by exactly it.
+ (1..6).each do |n|
+ account = provider_sync!(
+ @plaid_account,
+ on: day(n),
+ reading: 1000 - (100 * (n - 1)),
+ imports: n == 1 ? [] : [ { date: day(n - 1), amount: 100, name: "Day #{n - 1} spend" } ]
+ )
+ end
+
+ materialize!(account)
+
+ assert_equal 500, balance_on(account, day(6))
+ assert_equal 900, balance_on(account, day(1))
+
+ visible = user_visible_valuation_entries(account)
+
+ assert_operator visible.count, :<=, 1,
+ "after six explained syncs the user should see at most the live reading, " \
+ "not a daily balance-update entry and not a leftover unsettled reading " \
+ "(saw: #{visible.map { |e| [ e.date.to_s, e.name, e.amount.to_i ] }.inspect})"
+ end
+
+ # Liability sign math and multi-day gaps must still explain the move.
+ test "a liability reading survives a multi-day gap with the right sign math" do
+ card_plaid_account = create_credit_card_plaid_account
+
+ account = provider_sync!(card_plaid_account, on: day(1), reading: 500)
+ assert_equal "liability", account.classification
+
+ seed_opening_balance(500, account: account)
+
+ # Three days later: the backlog arrives, including the purchase that posted after day
+ # one's reading. 500 + 30 + 20 - 100 = 450.
+ account = provider_sync!(
+ card_plaid_account,
+ on: day(4),
+ reading: 450,
+ imports: [
+ { date: day(1), amount: 30, name: "Purchase" },
+ { date: day(2), amount: 20, name: "Purchase" },
+ { date: day(3), amount: -100, name: "Payment" }
+ ]
+ )
+
+ materialize!(account)
+
+ assert_equal 530, balance_on(account, day(1)),
+ "day one closed at 530: the reading was taken before the 30 purchase posted"
+ assert_equal 550, balance_on(account, day(2))
+ assert_equal 450, balance_on(account, day(3))
+ assert_equal 450, balance_on(account, day(4))
+ assert_equal 500, balance_on(account, day(0)),
+ "days before the gap must not shift because of the backlog"
+
+ account = provider_sync!(card_plaid_account, on: day(5), reading: 450)
+ materialize!(account)
+
+ assert_equal 530, balance_on(account, day(1))
+ assert_equal 500, balance_on(account, day(0))
+ assert_equal 450, balance_on(account, day(5))
+ end
+
+ # Repeated same-day syncs must not accumulate rows or freeze intra-day readings.
+ test "repeat syncs on the same day neither accumulate rows nor freeze intra-day readings" do
+ provider_sync!(@plaid_account, on: day(1), reading: 1000)
+
+ account = provider_sync!(
+ @plaid_account,
+ on: day(2),
+ reading: 900,
+ imports: [ { date: day(1), amount: 100, name: "Yesterday's spend" } ]
+ )
+
+ rows_after_first_cycle = user_visible_valuation_entries(account).count
+
+ provider_sync!(
+ @plaid_account,
+ on: day(2),
+ reading: 880,
+ imports: [ { date: day(2), amount: 20, name: "Today's spend" } ]
+ )
+ account = provider_sync!(@plaid_account, on: day(2), reading: 880)
+
+ assert_operator user_visible_valuation_entries(account).count, :<=, rows_after_first_cycle,
+ "extra sync cycles on the same day must not add valuation rows the user can see"
+
+ valuation_dates = user_visible_valuation_entries(account).map(&:date)
+ assert_equal valuation_dates.uniq.size, valuation_dates.size,
+ "the same date must never end up with more than one valuation row"
+
+ materialize!(account)
+
+ assert_equal 880, balance_on(account, day(2))
+ assert_equal 900, balance_on(account, day(1)),
+ "day one closed at 900; no intra-day reading may override that"
+ end
+
+ private
+ # day(1) is "day one" in the scenarios above; day(0) is the day before it.
+ def day(offset)
+ @day_one + (offset - 1).days
+ end
+
+ def sync_clock(date)
+ Time.zone.parse("#{date} #{SYNC_TIME_OF_DAY}")
+ end
+
+ # Always hand back a freshly loaded Account: Account::Anchorable memoizes its
+ # CurrentBalanceManager (which in turn memoizes its anchor lookup), so a long-lived
+ # instance would read state from before the sync under test.
+ def account_for(plaid_account)
+ Account.find(PlaidAccount.find(plaid_account.id).current_account.id)
+ end
+
+ # One full provider cycle, driven through the real processor so the implementation - not
+ # this test - decides whether the balance reading is taken before or after the batch is
+ # imported. Returns a fresh Account.
+ def provider_sync!(plaid_account, on:, reading:, imports: [])
+ travel_to sync_clock(on) do
+ PlaidAccount.find(plaid_account.id).update!(
+ current_balance: reading,
+ available_balance: reading
+ )
+
+ imported = []
+ stub_provider_subprocessors(plaid_account, imports, imported)
+
+ PlaidAccount::Processor.new(PlaidAccount.find(plaid_account.id)).process
+
+ # PlaidAccount::Processor#process_transactions swallows exceptions, so prove the
+ # batch actually landed instead of vanishing into a rescue.
+ assert_equal imports.size, imported.size,
+ "the provider's transaction batch did not import on #{on}"
+ end
+
+ account_for(plaid_account)
+ end
+
+ # Replaces only the transaction importer with a stand-in that creates this cycle's
+ # entries, at exactly the point in the processor where the real import happens. The other
+ # product sub-processors are no-ops (nothing in these scenarios needs holdings, trades or
+ # liability statements).
+ def stub_provider_subprocessors(plaid_account, imports, imported)
+ importer = Object.new
+ importer.define_singleton_method(:process) do
+ imports.each do |txn|
+ account = Account.find(PlaidAccount.find(plaid_account.id).current_account.id)
+
+ entry = account.entries.create!(
+ date: txn[:date],
+ name: txn[:name] || "Imported transaction",
+ amount: txn[:amount],
+ currency: txn[:currency] || account.currency,
+ entryable: Transaction.new
+ )
+
+ imported << entry.id
+ end
+ end
+
+ PlaidAccount::Transactions::Processor.stubs(:new).returns(importer)
+ PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)
+ PlaidAccount::Investments::HoldingsProcessor.any_instance.stubs(:process)
+ PlaidAccount::Liabilities::CreditProcessor.any_instance.stubs(:process)
+ PlaidAccount::Liabilities::MortgageProcessor.any_instance.stubs(:process)
+ PlaidAccount::Liabilities::StudentLoanProcessor.any_instance.stubs(:process)
+ end
+
+ # Gives the account a history to be wrong about: without an opening anchor the reverse
+ # walk stops at the oldest entry and there are no "earlier days" to inflate.
+ def seed_opening_balance(amount, account: nil)
+ account ||= accounts(:connected)
+
+ account.entries.create!(
+ date: day(-4),
+ name: "Opening balance",
+ amount: amount,
+ currency: account.currency,
+ entryable: Valuation.new(kind: "opening_anchor")
+ )
+
+ Account.find(account.id)
+ end
+
+ def create_credit_card_plaid_account
+ PlaidAccount.create!(
+ plaid_item: plaid_items(:one),
+ plaid_id: "acc_mock_credit_card",
+ name: "Test Credit Card",
+ plaid_type: "credit",
+ plaid_subtype: "credit card",
+ currency: "USD",
+ current_balance: 500,
+ available_balance: 500
+ )
+ end
+
+ def materialize!(account)
+ Balance::Materializer.new(Account.find(account.id), strategy: :reverse).materialize_balances
+ end
+
+ def balance_row(account, date)
+ row = Account.find(account.id).balances.find_by(date: date, currency: account.currency)
+ assert_not_nil row, "expected a materialized balance for #{date}"
+ row
+ end
+
+ def balance_on(account, date)
+ balance_row(account, date).balance
+ end
+
+ # What the user actually sees: AccountsController#show builds the activity list from
+ # `account.entries.excluding_split_parents.search(@q)` with no filter on entryable_type
+ # or Valuation#kind, and entries/_entry.html.erb renders a valuation through the same row
+ # template as a transaction. So every valuation entry here is a visible line item.
+ def user_visible_valuation_entries(account)
+ Account.find(account.id)
+ .entries
+ .excluding_split_parents
+ .where(entryable_type: "Valuation")
+ .order(:date)
+ end
+end
diff --git a/test/models/account/current_balance_manager_test.rb b/test/models/account/current_balance_manager_test.rb
index de261219ec..f2788c9bcf 100644
--- a/test/models/account/current_balance_manager_test.rb
+++ b/test/models/account/current_balance_manager_test.rb
@@ -11,6 +11,9 @@ class Account::CurrentBalanceManagerTest < ActiveSupport::TestCase
provider_type: "PlaidAccount",
provider_id: plaid_accounts(:one).id
)
+
+ # The reuse of an explained anchor is gated on BALANCE_REUSE_EXPLAINED_ANCHOR (default off).
+ Rails.configuration.x.balance.stubs(:reuse_explained_anchor).returns(true)
end
# -------------------------------------------------------------------------------------------------
@@ -207,7 +210,6 @@ class Account::CurrentBalanceManagerTest < ActiveSupport::TestCase
assert_equal 1000, @linked_account.balance
end
-
# A provider whose figures come from a statement knows the day they describe,
# which is not always today.
test "anchors a linked account balance on the date it is given" do
@@ -264,40 +266,439 @@ class Account::CurrentBalanceManagerTest < ActiveSupport::TestCase
assert_equal 1500, entry.amount
end
- test "preserves previous day anchor as reconciliation when updating linked account balance" do
- # First create a current anchor
+ test "moves a stale anchor forward when the imported ledger explains the balance change" do
+ day_one = Date.current
manager = Account::CurrentBalanceManager.new(@linked_account)
- result = manager.set_current_balance(1000)
- assert result.success?
+ assert manager.set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ # Processors now import transactions BEFORE anchoring, so day one's entries are
+ # already persisted by the time set_current_balance judges the old anchor.
+ @linked_account.entries.create!(
+ date: day_one,
+ name: "Card payment",
+ amount: 400,
+ currency: "USD",
+ entryable: Transaction.new
+ )
- current_anchor = @linked_account.valuations.current_anchor.first
- original_id = current_anchor.id
+ day_two_manager = Account::CurrentBalanceManager.new(@linked_account)
- # Travel to tomorrow to ensure date change
- travel_to Date.current + 1.day do
- # Now update it
+ # The anchor just moves forward in place: no destroy, no create. Net row delta
+ # is ZERO.
+ assert_no_difference -> { @linked_account.entries.count } do
+ assert_no_difference -> { @linked_account.valuations.count } do
+ assert day_two_manager.set_current_balance(600).success?
+ end
+ end
+
+ moved = Valuation.find(stale_id)
+ assert_equal "current_anchor", moved.kind
+ assert_equal 600, moved.entry.amount
+ assert_equal Date.current, moved.entry.date
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ assert_empty @linked_account.valuations.reconciliation
+ end
+ end
+
+ # With BALANCE_REUSE_EXPLAINED_ANCHOR off (the default), the ledger is never consulted and
+ # every stale anchor rotates into a reconciliation waypoint, as it did before this gate.
+ test "preserves a stale anchor as a waypoint when the explained-anchor reuse flag is off" do
+ Rails.configuration.x.balance.stubs(:reuse_explained_anchor).returns(false)
+
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ @linked_account.entries.create!(
+ date: day_one,
+ name: "Card payment",
+ amount: 400,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(600).success?
+
+ preserved = Valuation.find(stale_id)
+ assert_equal "reconciliation", preserved.kind
+ assert_equal 1000, preserved.entry.amount
+ assert_equal day_one, preserved.entry.date
+
+ anchors = @linked_account.valuations.current_anchor
+ assert_equal 1, anchors.count
+ assert_equal 600, anchors.first.entry.amount
+ assert_equal Date.current, anchors.first.entry.date
+ end
+ end
+
+ test "records a partial-import reading without reusing an explained anchor" do
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ @linked_account.entries.create!(
+ date: day_one,
+ name: "Card payment",
+ amount: 400,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ result = Account::CurrentBalanceManager.new(@linked_account).set_current_balance(
+ 600,
+ reuse_explained_anchor: false
+ )
+
+ assert result.success?
+ preserved = Valuation.find(stale_id)
+ assert_equal "reconciliation", preserved.kind
+ assert_equal 1000, preserved.entry.amount
+ assert_equal day_one, preserved.entry.date
+
+ anchors = @linked_account.valuations.current_anchor
+ assert_equal 1, anchors.count
+ assert_equal 600, anchors.first.entry.amount
+ assert_equal Date.current, anchors.first.entry.date
+ end
+ end
+
+ # An anchor moved forward in place carries the flows dated on its new date inside its own
+ # amount. Re-summing that date on the next sync counts them twice, makes the move look
+ # unexplained, and freezes a mid-day reading as a waypoint - the #1492 / #1484 corruption
+ # this change exists to remove. Needs three syncs to reach; no other test goes that far.
+ test "an anchor already moved forward in place is not double counted on the next sync" do
+ day_one = Date.current
+ day_two = day_one + 1.day
+ day_three = day_one + 2.days
+
+ # Day one, 02:22: the provider reports 1000 and nothing has posted yet.
+ travel_to Time.zone.parse("#{day_one} 02:22") do
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ end
+
+ anchor_id = @linked_account.valuations.current_anchor.first.id
+
+ # Day two, 02:22: yesterday's 400 arrives in today's batch. The ledger explains
+ # 1000 -> 600, so the anchor moves forward IN PLACE to day two / 600.
+ travel_to Time.zone.parse("#{day_two} 02:22") do
+ @linked_account.entries.create!(
+ date: day_one,
+ name: "Day 1 spend",
+ amount: 400,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(600).success?
+ end
+
+ # Precondition for the bug, asserted rather than assumed.
+ assert_equal "current_anchor", Valuation.find(anchor_id).kind
+ assert_equal day_two, Valuation.find(anchor_id).entry.date
+
+ # Day two, 14:00: a second cycle the same day. 100 posts, dated to day two, and the
+ # reading drops to 500. Same-day update, so the anchor's amount now BAKES IN that 100.
+ travel_to Time.zone.parse("#{day_two} 14:00") do
+ @linked_account.entries.create!(
+ date: day_two,
+ name: "Day 2 spend (early)",
+ amount: 100,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(500).success?
+ end
+
+ assert_equal 500, Valuation.find(anchor_id).entry.amount
+ assert_equal day_two, Valuation.find(anchor_id).entry.date
+
+ # Day three, 02:22: the 50 that posted after yesterday's last reading arrives, dated
+ # to day two. True day-two close = 1000 - 400 - 100 - 50 = 450, and 450 is exactly what
+ # the provider now reports. The only flow NOT already inside the anchor's 500 is that 50,
+ # so the ledger fully explains 500 -> 450 and the anchor should just move forward again.
+ travel_to Time.zone.parse("#{day_three} 02:22") do
+ @linked_account.entries.create!(
+ date: day_two,
+ name: "Day 2 spend (late)",
+ amount: 50,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(450).success?
+
+ moved = Valuation.find(anchor_id)
+ assert_equal "current_anchor", moved.kind,
+ "the day-two 100 is already inside the anchor's 500; re-summing it makes an explained " \
+ "move look unexplained and freezes a mid-day reading as a waypoint"
+ assert_empty @linked_account.valuations.reconciliation
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ assert_equal day_three, moved.entry.date
+ assert_equal 450, moved.entry.amount
+ end
+ end
+
+ # A split replaces a transaction already inside the anchor with child rows created
+ # afterwards. The children must use the parent's timestamp, not their own, or an
+ # unchanged reading looks unexplained and the stale anchor is preserved.
+ test "a split of a transaction already inside the anchor does not make an unchanged reading look unexplained" do
+ day_one = Date.current
+ parent = @linked_account.entries.create!(
+ date: day_one,
+ name: "Split purchase",
+ amount: 25,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(100).success?
+ anchor_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ @linked_account.entries.create!(
+ date: day_one,
+ name: "Split A",
+ amount: 10,
+ currency: "USD",
+ entryable: Transaction.new,
+ parent_entry: parent
+ )
+ @linked_account.entries.create!(
+ date: day_one,
+ name: "Split B",
+ amount: 15,
+ currency: "USD",
+ entryable: Transaction.new,
+ parent_entry: parent
+ )
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(100).success?
+
+ moved = Valuation.find(anchor_id)
+ assert_equal "current_anchor", moved.kind
+ assert_equal 100, moved.entry.amount
+ assert_equal day_one + 1.day, moved.entry.date
+ assert_empty @linked_account.valuations.reconciliation
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ end
+ end
+
+ # `current_anchor_valuation` picks the newest of several anchor rows, but max_by over an
+ # unordered query needs an explicit tiebreak to resolve a same-date tie. Duplicates are
+ # reachable: the only guard is Entry's app-level date uniqueness validation (no DB index).
+ test "current anchor lookup resolves a same-date duplicate to the newest row" do
+ anchor_name = Valuation.build_current_anchor_name(@linked_account.accountable_type)
+
+ @linked_account.entries.create!(
+ date: Date.current,
+ name: anchor_name,
+ amount: 100,
+ currency: "USD",
+ entryable: Valuation.new(kind: "current_anchor")
+ )
+
+ # How such a row exists in production: pre-dating the validation, inserted via raw SQL,
+ # or written by a second in-flight transaction that could not see the first one commit.
+ duplicate = @linked_account.entries.new(
+ date: Date.current,
+ name: anchor_name,
+ amount: 9999,
+ currency: "USD",
+ entryable: Valuation.new(kind: "current_anchor")
+ )
+ duplicate.save!(validate: false)
+
+ assert_equal 2, @linked_account.valuations.current_anchor.count
+
+ manager = Account::CurrentBalanceManager.new(@linked_account)
+
+ assert_equal 9999, manager.current_balance,
+ "with two anchors tied on date the newest row must win"
+ end
+
+ test "preserves a stale anchor when the explaining window mixes currencies" do
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ @linked_account.entries.create!(
+ date: day_one,
+ name: "Foreign card payment",
+ amount: 400,
+ currency: "EUR",
+ entryable: Transaction.new
+ )
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(600).success?
+
+ assert_equal "reconciliation", Valuation.find(stale_id).kind
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ end
+ end
+
+ # A provider can correct an account's currency between syncs, leaving the standing anchor's
+ # own entry denominated in the old code. Rotating is the only path that replaces it with a
+ # reading in the current currency.
+ test "preserves a stale anchor whose own currency no longer matches the account" do
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+ assert_equal "USD", Valuation.find(stale_id).entry.currency
+
+ travel_to day_one + 1.day do
+ # No transactions were imported, so the flow window is empty and the flow-currency
+ # check passes vacuously.
+ @linked_account.update!(currency: "EUR")
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+
+ assert_equal "reconciliation", Valuation.find(stale_id).kind
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+
+ fresh = @linked_account.valuations.current_anchor.first
+ assert_equal "EUR", fresh.entry.currency
+ assert_equal day_one + 1.day, fresh.entry.date
+ end
+ end
+
+ test "preserves a stale-currency anchor even when every flow matches the new currency" do
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ @linked_account.update!(currency: "EUR")
+ @linked_account.entries.create!(
+ date: day_one + 1.day,
+ name: "Coffee",
+ amount: 20,
+ currency: "EUR",
+ entryable: Transaction.new
+ )
+
+ # 1000 - 20 == 980 satisfies the ledger identity numerically, but the 1000 is USD.
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(980).success?
+
+ assert_equal "reconciliation", Valuation.find(stale_id).kind
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ assert_equal "EUR", @linked_account.valuations.current_anchor.first.entry.currency
+ end
+ end
+
+ test "does not move a stale anchor forward on an investment account" do
+ investment = accounts(:investment)
+ investment.update!(plaid_account: plaid_accounts(:one))
+ assert investment.linked?
+
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(investment).set_current_balance(1000).success?
+ stale_id = investment.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ investment.entries.create!(date: day_one, name: "Withdrawal", amount: 400, currency: "USD", entryable: Transaction.new)
+
+ assert Account::CurrentBalanceManager.new(investment).set_current_balance(600).success?
+
+ assert_equal "reconciliation", Valuation.find(stale_id).kind
+ assert_equal 1, investment.valuations.current_anchor.count
+ end
+ end
+
+ # The tolerance in ledger_explains? is the account currency's minor unit, not a fixed 0.01.
+ # BHD has 3 decimal places (step 0.001), so a reading exactly one minor unit off the
+ # ledger-predicted balance is still "explained" and the anchor moves forward in place.
+ test "moves a stale anchor forward when it is off by exactly one BHD minor unit" do
+ @linked_account.update!(currency: "BHD")
+
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ # No ledger flows: the expected balance stays at 1000. 999.999 is exactly 0.001 (one
+ # BHD minor unit) away, which is at the accepted threshold.
+ assert_no_difference -> { @linked_account.entries.count } do
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(999.999).success?
+ end
+
+ moved = Valuation.find(stale_id)
+ assert_equal "current_anchor", moved.kind
+ assert_equal BigDecimal("999.999"), moved.entry.amount
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ assert_empty @linked_account.valuations.reconciliation
+ end
+ end
+
+ # One tick beyond the BHD minor unit is a genuine unexplained move, and must NOT be
+ # swallowed by a coarser, USD-shaped 0.01 tolerance.
+ test "preserves a stale anchor when it is off by just beyond one BHD minor unit" do
+ @linked_account.update!(currency: "BHD")
+
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ # 999.998 is 0.002 away from the expected 1000: beyond BHD's 0.001 minor unit.
assert_difference -> { @linked_account.entries.count } => 1,
- -> { @linked_account.valuations.count } => 1 do
- result = manager.set_current_balance(2000)
- assert result.success?
- assert result.changes_made?
+ -> { @linked_account.valuations.count } => 1 do
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(999.998).success?
end
- # The old anchor should now be a reconciliation
- preserved_valuation = Valuation.find(original_id)
- assert_equal "reconciliation", preserved_valuation.kind
- assert_equal 1000, preserved_valuation.entry.amount
- assert_equal Valuation.build_reconciliation_name(@linked_account.accountable_type), preserved_valuation.entry.name
- assert_equal Date.yesterday, preserved_valuation.entry.date
-
- # A new current anchor should exist for today
- new_anchor = @linked_account.valuations.current_anchor.first
- assert_not_equal original_id, new_anchor.id
- assert_equal 2000, new_anchor.entry.amount
- assert_equal Date.current, new_anchor.entry.date
+ preserved = Valuation.find(stale_id)
+ assert_equal "reconciliation", preserved.kind
+ assert_equal 1, @linked_account.valuations.current_anchor.count
end
+ end
+
+ # JPY has 0 decimal places (step 1), a coarser granularity than the fixed 0.01 the old
+ # tolerance used. A reading exactly one JPY unit off is still "explained".
+ test "moves a stale anchor forward when it is off by exactly one JPY minor unit" do
+ @linked_account.update!(currency: "JPY")
- assert_equal 2000, @linked_account.balance
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ # No ledger flows: the expected balance stays at 1000. 999 is exactly 1 (one JPY
+ # minor unit) away, which is at the accepted threshold.
+ assert_no_difference -> { @linked_account.entries.count } do
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(999).success?
+ end
+
+ moved = Valuation.find(stale_id)
+ assert_equal "current_anchor", moved.kind
+ assert_equal 999, moved.entry.amount
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ assert_empty @linked_account.valuations.reconciliation
+ end
+ end
+
+ # One tick beyond the JPY minor unit is a genuine unexplained move.
+ test "preserves a stale anchor when it is off by just beyond one JPY minor unit" do
+ @linked_account.update!(currency: "JPY")
+
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ # 998 is 2 away from the expected 1000: beyond JPY's minor unit of 1.
+ assert_difference -> { @linked_account.entries.count } => 1,
+ -> { @linked_account.valuations.count } => 1 do
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(998).success?
+ end
+
+ preserved = Valuation.find(stale_id)
+ assert_equal "reconciliation", preserved.kind
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ end
end
test "does not preserve same-day anchor as reconciliation" do
@@ -335,6 +736,81 @@ class Account::CurrentBalanceManagerTest < ActiveSupport::TestCase
assert_equal 1500, @linked_account.balance
end
+ # Arnau's first scenario: a transaction that posts after the reading, dated the
+ # reading's day, arrives in the next sync and explains the move.
+ test "a late-posted same-day transaction explains the stale anchor" do
+ day_one = Date.current
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ anchor_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ Account::ProviderImportAdapter.new(@linked_account).import_transaction(
+ external_id: "late-posted",
+ amount: 20,
+ currency: "USD",
+ date: day_one,
+ name: "Late payment",
+ source: "plaid",
+ extra: { "plaid" => { "pending" => false } }
+ )
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(980).success?
+
+ moved = Valuation.find(anchor_id)
+ assert_equal "current_anchor", moved.kind
+ assert_equal 980, moved.entry.amount
+ assert_equal day_one + 1.day, moved.entry.date
+ assert_empty @linked_account.valuations.reconciliation
+ end
+ end
+
+ # Arnau's second scenario: a pending row exists before the anchor, then the
+ # provider claims it in place. Its created_at stays before the anchor, so the
+ # current watermark excludes it and the stale anchor is preserved. This pins
+ # the known limitation; update these assertions when the pending-basis
+ # follow-up lands.
+ test "a pending row claimed in place keeps the stale anchor as a known limitation" do
+ day_one = Date.current
+ adapter = Account::ProviderImportAdapter.new(@linked_account)
+ pending = adapter.import_transaction(
+ external_id: "pending-400",
+ amount: 400,
+ currency: "USD",
+ date: day_one,
+ name: "Pending card payment",
+ source: "plaid",
+ extra: { "plaid" => { "pending" => true } }
+ )
+ assert pending.transaction.pending?
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(1000).success?
+ stale_id = @linked_account.valuations.current_anchor.first.id
+
+ travel_to day_one + 1.day do
+ claimed = adapter.import_transaction(
+ external_id: "posted-400",
+ amount: 400,
+ currency: "USD",
+ date: Date.current,
+ name: "Posted card payment",
+ source: "plaid",
+ pending_transaction_id: "pending-400",
+ extra: { "plaid" => { "pending" => false, "pending_transaction_id" => "pending-400" } }
+ )
+ assert_equal pending.id, claimed.id
+ assert_not claimed.transaction.reload.pending?
+
+ assert Account::CurrentBalanceManager.new(@linked_account).set_current_balance(600).success?
+
+ preserved = Valuation.find(stale_id)
+ assert_equal "reconciliation", preserved.kind
+ assert_equal 1000, preserved.entry.amount
+ assert_equal day_one, preserved.entry.date
+ assert_equal 1, @linked_account.valuations.current_anchor.count
+ assert_equal 600, @linked_account.valuations.current_anchor.first.entry.amount
+ end
+ end
+
test "current_balance returns balance from current anchor" do
manager = Account::CurrentBalanceManager.new(@linked_account)
diff --git a/test/models/enable_banking_account_processor_test.rb b/test/models/enable_banking_account_processor_test.rb
index 320e7f7e1a..626060d1ce 100644
--- a/test/models/enable_banking_account_processor_test.rb
+++ b/test/models/enable_banking_account_processor_test.rb
@@ -50,6 +50,53 @@ class EnableBankingAccountProcessorTest < ActiveSupport::TestCase
assert_equal BigDecimal("250"), acct.reload.cash_balance
end
+ test "anchors the current balance only after transactions have been imported" do
+ eb_acct = @item.enable_banking_accounts.create!(
+ name: "Checking",
+ uid: "eb_4",
+ currency: "GBP",
+ current_balance: BigDecimal("250")
+ )
+
+ acct = accounts(:depository)
+ acct.update!(balance: 500, cash_balance: 500, currency: "GBP")
+ AccountProvider.create!(account: acct, provider: eb_acct)
+
+ baseline_transaction_count = acct.entries.transactions.count
+
+ # Stand-in transaction importer: creates one entry, the way a real provider batch
+ # would, so we can observe whether it landed before the anchor was written. Mocha
+ # evaluates a `.with` block as a parameter matcher, which can run more than once per
+ # invocation, so the side effect is guarded to fire only the first time.
+ imported = false
+ EnableBankingAccount::Transactions::Processor.any_instance.stubs(:process).with do
+ unless imported
+ imported = true
+ acct.entries.create!(
+ date: Date.current,
+ name: "Imported transaction",
+ amount: 10,
+ currency: "GBP",
+ entryable: Transaction.new
+ )
+ end
+ true
+ end.returns({ success: true })
+
+ observed_transaction_count = nil
+
+ Account.any_instance.stubs(:set_current_balance).with do
+ observed_transaction_count ||= acct.entries.transactions.count
+ true
+ end.returns(Account::CurrentBalanceManager::Result.new(success?: true, changes_made?: true, error: nil))
+
+ EnableBankingAccount::Processor.new(eb_acct).process
+
+ assert_equal baseline_transaction_count + 1, observed_transaction_count,
+ "set_current_balance must be called AFTER the sync's transactions are persisted, " \
+ "so a stale anchor can be judged against a complete ledger"
+ end
+
test "snapshot upsert preserves an established currency when the payload omits it" do
eb_acct = @item.enable_banking_accounts.create!(name: "Checking", uid: "eb_3", currency: "GBP")
diff --git a/test/models/indexa_capital_account/activities_processor_test.rb b/test/models/indexa_capital_account/activities_processor_test.rb
index 8f28299acc..1101502c86 100644
--- a/test/models/indexa_capital_account/activities_processor_test.rb
+++ b/test/models/indexa_capital_account/activities_processor_test.rb
@@ -160,7 +160,7 @@ class IndexaCapitalAccount::ActivitiesProcessorTest < ActiveSupport::TestCase
processor = IndexaCapitalAccount::ActivitiesProcessor.new(@indexa_capital_account)
result = processor.process
- assert_equal({ trades: 0, transactions: 0 }, result)
+ assert_equal({ trades: 0, transactions: 0, failed: 0 }, result)
end
private
diff --git a/test/models/plaid_account/investments/holdings_processor_test.rb b/test/models/plaid_account/investments/holdings_processor_test.rb
index 01194cccfe..d5e9d03501 100644
--- a/test/models/plaid_account/investments/holdings_processor_test.rb
+++ b/test/models/plaid_account/investments/holdings_processor_test.rb
@@ -70,6 +70,47 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
assert_equal Date.current, holdings.second.date
end
+ test "uses the supplied snapshot currency when a holding omits its own currency" do
+ account = @plaid_account.current_account
+ account.update!(currency: "USD")
+ holding_date = 5.days.ago.to_date
+ @plaid_account.update!(
+ currency: "EUR",
+ raw_holdings_payload: {
+ securities: [],
+ holdings: [
+ {
+ "security_id" => "123",
+ "quantity" => 1,
+ "institution_price" => 10,
+ "institution_price_as_of" => holding_date
+ }
+ ],
+ transactions: []
+ }
+ )
+
+ @security_resolver.expects(:resolve)
+ .with(plaid_security_id: "123")
+ .returns(
+ OpenStruct.new(
+ security: securities(:aapl),
+ cash_equivalent?: false,
+ brokerage_cash?: false
+ )
+ )
+
+ processor = PlaidAccount::Investments::HoldingsProcessor.new(
+ @plaid_account,
+ security_resolver: @security_resolver,
+ currency: @plaid_account.currency
+ )
+ processor.process
+
+ holding = Holding.find_by!(account: account, security: securities(:aapl), date: holding_date)
+ assert_equal "EUR", holding.currency
+ end
+
# Plaid does not delete future holdings because it doesn't support holdings deletion
# (PlaidAdapter#can_delete_holdings? returns false). This test verifies that future
# holdings are NOT deleted when processing Plaid holdings data.
diff --git a/test/models/redbark_account/processor_test.rb b/test/models/redbark_account/processor_test.rb
index 9a26c274ff..bb5f24ebbc 100644
--- a/test/models/redbark_account/processor_test.rb
+++ b/test/models/redbark_account/processor_test.rb
@@ -372,6 +372,41 @@ class RedbarkAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal 0, result[:total]
end
+ test "partial transaction import still records the provider reading without reusing the old anchor" do
+ Account.any_instance.stubs(:sync_later)
+ account, ra = link(Depository, provider: "fiskil", balance: "600")
+ day_one = Date.current - 1.day
+ ra.update!(raw_transactions_payload: [ { "id" => "tx_partial", "amount" => "-400.00", "date" => Date.current.to_s } ])
+
+ travel_to day_one do
+ account.entries.create!(
+ date: day_one,
+ name: "Late outflow",
+ amount: 400,
+ currency: @currency,
+ entryable: Transaction.new
+ )
+ account.set_current_balance(1000, schedule_sync: false)
+ end
+
+ RedbarkAccount::Transactions::Processor.any_instance.stubs(:process).returns(
+ { success: false, total: 1, imported: 0, skipped: 0, failed: 1, errors: [] }
+ )
+
+ RedbarkAccount::Processor.new(ra).process
+
+ assert_equal BigDecimal("600"), account.reload.balance
+ anchors = account.valuations.current_anchor
+ assert_equal 1, anchors.count
+ assert_equal BigDecimal("600"), anchors.first.entry.amount
+ assert_equal Date.current, anchors.first.entry.date
+
+ preserved = account.valuations.reconciliation.first
+ assert_not_nil preserved
+ assert_equal BigDecimal("1000"), preserved.entry.amount
+ assert_equal day_one, preserved.entry.date
+ end
+
private
def link(accountable_class, provider:, balance:)
diff --git a/test/models/sophtron_account_processor_test.rb b/test/models/sophtron_account_processor_test.rb
index 3a327cad8c..03784ef35e 100644
--- a/test/models/sophtron_account_processor_test.rb
+++ b/test/models/sophtron_account_processor_test.rb
@@ -20,7 +20,7 @@ class SophtronAccountProcessorTest < ActiveSupport::TestCase
[ -25, 25 ].each do |observed|
sophtron_account.update!(balance: observed)
- SophtronAccount::Processor.new(sophtron_account).process_account!
+ SophtronAccount::Processor.new(sophtron_account).process
assert_equal BigDecimal("-25"), acct.reload.balance
assert_equal BigDecimal("-25"), acct.current_anchor_balance
@@ -37,7 +37,7 @@ class SophtronAccountProcessorTest < ActiveSupport::TestCase
[ -25, 25 ].each do |observed|
sophtron_account.update!(balance: observed)
- SophtronAccount::Processor.new(sophtron_account).process_account!
+ SophtronAccount::Processor.new(sophtron_account).process
assert_equal BigDecimal("25"), acct.reload.balance
end
@@ -50,7 +50,7 @@ class SophtronAccountProcessorTest < ActiveSupport::TestCase
)
acct = link_account(accounts(:depository), sophtron_account)
- SophtronAccount::Processor.new(sophtron_account).process_account!
+ SophtronAccount::Processor.new(sophtron_account).process
assert_equal BigDecimal("1000.00"), acct.reload.balance
end
@@ -62,7 +62,7 @@ class SophtronAccountProcessorTest < ActiveSupport::TestCase
)
acct = link_account(accounts(:loan), sophtron_account)
- SophtronAccount::Processor.new(sophtron_account).process_account!
+ SophtronAccount::Processor.new(sophtron_account).process
assert_equal BigDecimal("400"), acct.reload.balance
end
@@ -83,6 +83,38 @@ class SophtronAccountProcessorTest < ActiveSupport::TestCase
assert_equal BigDecimal("50"), acct.current_anchor_balance
end
+ test "anchors the balance after transactions have been imported" do
+ sophtron_account = create_sophtron_account(account_id: "dep_order", balance: BigDecimal("600"))
+ acct = link_account(accounts(:depository), sophtron_account)
+ acct.set_current_balance(1000, schedule_sync: false)
+
+ imported = false
+ SophtronAccount::Transactions::Processor.any_instance.stubs(:process).with do
+ unless imported
+ imported = true
+ acct.entries.create!(
+ date: Date.current,
+ name: "Late outflow",
+ amount: 400,
+ currency: "USD",
+ entryable: Transaction.new
+ )
+ end
+ true
+ end.returns({ success: true, total: 1, imported: 1, failed: 0, errors: [] })
+
+ imported_entry_visible = false
+ Account.any_instance.stubs(:set_current_balance).with do
+ imported_entry_visible = acct.entries.transactions.where(name: "Late outflow").exists?
+ true
+ end.returns(Account::CurrentBalanceManager::Result.new(success?: true, changes_made?: true, error: nil))
+
+ SophtronAccount::Processor.new(sophtron_account).process
+
+ assert imported_entry_visible,
+ "set_current_balance must run after the transaction batch is persisted"
+ end
+
test "historical observations preserve current balance and cash balance" do
sophtron_account = create_sophtron_account(account_id: "cc_future_anchor", balance: -25)
acct = link_account(accounts(:credit_card), sophtron_account)