The personal finance app for everyone (by everyone)
Ruby
Fix SimpleFIN inverting Loan account balances (#1574)
GermanDZ7c14c80444c3
diff --git a/app/models/simplefin_account/processor.rb b/app/models/simplefin_account/processor.rbindex f9ef876414..98cba64973 100644--- a/app/models/simplefin_account/processor.rb+++ b/app/models/simplefin_account/processor.rb@@ -80,57 +80,90 @@ class SimplefinAccount::Processorbalance = observedif is_liability- # 1) Try transaction-history heuristic when enabled- begin- result = SimplefinAccount::Liabilities::OverpaymentAnalyzer- .new(simplefin_account, observed_balance: observed)- .call-- case result.classification- when :credit- balance = -observed.abs- Rails.logger.info(- "SimpleFIN overpayment heuristic: classified as credit for sfa=#{simplefin_account.id}, " \- "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"- )- Sentry.add_breadcrumb(Sentry::Breadcrumb.new(- category: "simplefin",- message: "liability_sign=credit",- data: { sfa_id: simplefin_account.id, observed: observed.to_s("F") }- )) rescue nil- when :debt- balance = observed.abs- Rails.logger.info(- "SimpleFIN overpayment heuristic: classified as debt for sfa=#{simplefin_account.id}, " \- "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"- )- Sentry.add_breadcrumb(Sentry::Breadcrumb.new(- category: "simplefin",- message: "liability_sign=debt",- data: { sfa_id: simplefin_account.id, observed: observed.to_s("F") }- )) rescue nil- else- # 2) Fall back to existing sign-only logic (log unknown for observability)- begin- obs = {- reason: result.reason,- tx_count: result.metrics[:tx_count],- charges_total: result.metrics[:charges_total],- payments_total: result.metrics[:payments_total],- observed: observed.to_s("F")- }.compact- Rails.logger.info("SimpleFIN overpayment heuristic: unknown; falling back #{obs.inspect}")- rescue- # no-op+ # Loans report principal outstanding as a positive balance from the+ # bank's perspective. The OverpaymentAnalyzer is designed for credit-+ # like liabilities (where charges/payments distinguish debt vs.+ # credit) and returns :unknown for loans with no transaction+ # history, which then falls through to a fallback that negates the+ # observed value — inverting the meaning so the loan ends up+ # _adding_ to net worth instead of subtracting from it. Trust the+ # bank's sign for Loans and skip the heuristic.+ if account.accountable_type == "Loan"+ balance = observed.abs+ Rails.logger.info(+ "SimpleFIN liability sign: classification=loan sfa=#{simplefin_account.id}"+ )+ Rails.logger.debug(+ "SimpleFIN liability sign (loan) amounts: sfa=#{simplefin_account.id} " \+ "observed=#{observed.to_s('F')} stored=#{balance.to_s('F')}"+ )+ Sentry.add_breadcrumb(Sentry::Breadcrumb.new(+ category: "simplefin",+ message: "liability_sign=loan",+ data: { sfa_id: simplefin_account.id }+ )) rescue nil+ else+ # 1) Try transaction-history heuristic when enabled+ begin+ result = SimplefinAccount::Liabilities::OverpaymentAnalyzer+ .new(simplefin_account, observed_balance: observed)+ .call++ case result.classification+ when :credit+ balance = -observed.abs+ Rails.logger.info(+ "SimpleFIN overpayment heuristic: classified as credit for sfa=#{simplefin_account.id} " \+ "tx_count=#{result.metrics[:tx_count]}"+ )+ Rails.logger.debug(+ "SimpleFIN overpayment heuristic (credit) amounts: sfa=#{simplefin_account.id} " \+ "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"+ )+ Sentry.add_breadcrumb(Sentry::Breadcrumb.new(+ category: "simplefin",+ message: "liability_sign=credit",+ data: { sfa_id: simplefin_account.id }+ )) rescue nil+ when :debt+ balance = observed.abs+ Rails.logger.info(+ "SimpleFIN overpayment heuristic: classified as debt for sfa=#{simplefin_account.id} " \+ "tx_count=#{result.metrics[:tx_count]}"+ )+ Rails.logger.debug(+ "SimpleFIN overpayment heuristic (debt) amounts: sfa=#{simplefin_account.id} " \+ "observed=#{observed.to_s('F')} metrics=#{result.metrics.slice(:charges_total, :payments_total, :tx_count).inspect}"+ )+ Sentry.add_breadcrumb(Sentry::Breadcrumb.new(+ category: "simplefin",+ message: "liability_sign=debt",+ data: { sfa_id: simplefin_account.id }+ )) rescue nil+ else+ # 2) Fall back to existing sign-only logic (log unknown for observability)+ begin+ Rails.logger.info(+ "SimpleFIN overpayment heuristic: unknown for sfa=#{simplefin_account.id} " \+ "reason=#{result.reason} tx_count=#{result.metrics[:tx_count]}; falling back"+ )+ Rails.logger.debug(+ "SimpleFIN overpayment heuristic (unknown) amounts: sfa=#{simplefin_account.id} " \+ "observed=#{observed.to_s('F')} " \+ "charges_total=#{result.metrics[:charges_total]} payments_total=#{result.metrics[:payments_total]}"+ )+ rescue+ # no-op+ end+ balance = normalize_liability_balance(observed, bal, avail)end+ rescue NameError+ # Analyzer not loaded; keep legacy behavior+ balance = normalize_liability_balance(observed, bal, avail)+ rescue => e+ Rails.logger.warn("SimpleFIN overpayment heuristic error for sfa=#{simplefin_account.id}: #{e.class} - #{e.message}")balance = normalize_liability_balance(observed, bal, avail)end- rescue NameError- # Analyzer not loaded; keep legacy behavior- balance = normalize_liability_balance(observed, bal, avail)- rescue => e- Rails.logger.warn("SimpleFIN overpayment heuristic error for sfa=#{simplefin_account.id}: #{e.class} - #{e.message}")- balance = normalize_liability_balance(observed, bal, avail)endenddiff --git a/test/models/simplefin_account_processor_test.rb b/test/models/simplefin_account_processor_test.rbindex 0c6a33b887..b5361b3659 100644--- a/test/models/simplefin_account_processor_test.rb+++ b/test/models/simplefin_account_processor_test.rb@@ -64,6 +64,32 @@ class SimplefinAccountProcessorTest < ActiveSupport::TestCaseassert_equal BigDecimal("50000"), acct.reload.balanceend+ # Many banks (and most mortgage feeds) report the loan principal+ # outstanding as a positive number from the bank's books. The old+ # liability path ran every Loan through OverpaymentAnalyzer ++ # normalize_liability_balance, and the latter's fallback for+ # `:unknown` classifications returned `-observed`, flipping a+ # bank-reported `+50000` into `-50000`. That bug made loans _add_ to+ # net worth instead of subtracting, so this test pins the corrected+ # behaviour.+ test "preserves positive provider balance for loan liabilities" do+ sfin_acct = SimplefinAccount.create!(+ simplefin_item: @item,+ name: "Mortgage",+ account_id: "loan_2",+ currency: "USD",+ account_type: "mortgage",+ current_balance: BigDecimal("50000")+ )++ acct = accounts(:loan)+ acct.update!(simplefin_account: sfin_acct)++ SimplefinAccount::Processor.new(sfin_acct).send(:process_account!)++ assert_equal BigDecimal("50000"), acct.reload.balance+ end+test "positive provider balance (overpayment) becomes negative for credit card liabilities" dosfin_acct = SimplefinAccount.create!(simplefin_item: @item,