The personal finance app for everyone (by everyone)
Ruby
Redbark: normalise liability balance sign by provider (fiskil / plaid / other) (#3899)
jaysbeekay32af1da6ebaa
diff --git a/app/models/redbark_account.rb b/app/models/redbark_account.rbindex bf5d4f68ac..0bba72106b 100644--- a/app/models/redbark_account.rb+++ b/app/models/redbark_account.rb@@ -70,6 +70,79 @@ class RedbarkAccount < ApplicationRecordaccountend+ # Normalise a Redbark liability (CreditCard / Loan) `current_balance` into the+ # sign Sure stores: a positive amount owed (or a negative credit / overpaid+ # balance).+ #+ # Redbark does not normalise the sign across its upstream sources:+ # * Fiskil (AU / CDR) reports the amount owed as a negative balance.+ # Negate to store it as a positive amount owed (Redbark sample response:+ # credit card "\"-842.15\"").+ # * Plaid (US / CA) reports the amount owed as a POSITIVE balance for+ # credit and loan accounts (https://plaid.com/docs/api/accounts/).+ # Pass through unchanged. This is what the bug in we-promise/sure#3747+ # mis-applies a blind negation to, flipping every Plaid-sourced+ # liability and double-inflating net worth.+ # * Any other or blank `provider` keeps Fiskil's negation convention+ # (today's behaviour) AND records a DebugLogEntry on every call, so an+ # operator can confirm or correct the convention for the new source.+ #+ # The check keys off `provider`, NOT the currency or institution country:+ # the reporter of we-promise/sure#3747 confirms that their Wise+ # Plaid-sourced accounts carry AUD and EUR alongside USD (upstream comment+ # 5920931841).+ #+ # The processor calls this for liability accountable types only; do not+ # call it for Depository / Investment — their balances pass through+ # unchanged regardless of provider.+ #+ # @param balance [BigDecimal, Numeric] the raw `current_balance` value the+ # processor read off `#current_balance` for this account.+ # @param accountable_type [String] the accountable type of the Sure account+ # being updated (e.g. "CreditCard"). Used only for the support metadata.+ # @param account [Account, nil] the Sure account, when available — attached+ # to the DebugLogEntry capture so support can trace the affected account.+ # @return [BigDecimal, Numeric] the balance with the correct sign.+ def normalized_liability_balance(balance:, accountable_type: nil, account: nil)+ case (provider.presence&.downcase)+ when "fiskil"+ -balance+ when "plaid"+ balance+ else+ # Unknown / blank convention: keep the CDR convention (negate) and+ # record a DebugLogEntry so support can flag the source. Following+ # docs/llm-guides/providers.md, include category, level, message,+ # source, provider_key and useful structured metadata, and attach+ # family, account and account provider when available.+ # DebugLogEntry#capture is a safe no-op on error (log! is wrapped in+ # rescue), so a missing family or a capture failure cannot break a+ # balance update.+ DebugLogEntry.capture(+ category: "redbark_sync",+ level: "warn",+ message: "Redbark liability balance normalisation: unrecognised or blank " \+ "provider — kept the Fiskil/CDR convention (negate). Operator should " \+ "confirm the upstream source's sign convention before relying on " \+ "stored liability balances.",+ source: "RedbarkAccount::Processor",+ provider_key: provider.presence,+ family: redbark_item&.family,+ account: account,+ account_provider: account_provider,+ metadata: {+ redbark_account_id: id,+ redbark_account_redbark_id: redbark_account_id,+ provider: provider,+ accountable_type: accountable_type,+ balance_in: balance,+ balance_out: -balance+ }+ )+ -balance+ end+ end+# Idempotently create or update AccountProvider link# CRITICAL: After creation, reload association to avoid stale nildef ensure_account_provider!(linked_account)diff --git a/app/models/redbark_account/processor.rb b/app/models/redbark_account/processor.rbindex 4a915c0ada..14af0c2f54 100644--- a/app/models/redbark_account/processor.rb+++ b/app/models/redbark_account/processor.rb@@ -59,10 +59,17 @@ class RedbarkAccount::Processorend# Banking sign convention:- # - CreditCard and Loan accounts may need sign inversion- # Provider returns negative for positive balance, so we negate it+ # CreditCard and Loan balances are signed differently depending on the+ # upstream source (Fiskil/CDR — AU — reports the amount owed as a+ # negative balance; Plaid — US/CA — reports it as positive). The+ # provider-specific rule and the DebugLogEntry captured for an+ # unrecognised provider live on RedbarkAccount#normalized_liability_balance.if account.accountable_type == "CreditCard" || account.accountable_type == "Loan"- balance = -balance+ balance = redbark_account.normalized_liability_balance(+ accountable_type: account.accountable_type,+ balance: balance,+ account: account+ )endRails.logger.info "RedbarkAccount::Processor - Balance update: #{balance}"diff --git a/test/models/redbark_account/processor_test.rb b/test/models/redbark_account/processor_test.rbindex 4d0a6fd4ae..4ef87f9bfc 100644--- a/test/models/redbark_account/processor_test.rb+++ b/test/models/redbark_account/processor_test.rb@@ -3,66 +3,207 @@require "test_helper"class RedbarkAccount::ProcessorTest < ActiveSupport::TestCase+ # Sign-convention ground truth for the two providers Redbark ships in+ # production (see we-promise/sure#3747 and upstream comment 5920931841,+ # where the reporter confirms the literal `"plaid"` string):+ #+ # fiskil (AU / CDR) -> amount owed arrives NEGATIVE -> store as +amount+ # plaid (US / CA) -> amount owed arrives POSITIVE -> store as-is+ # unknown / blank -> keep fiskil's negation convention + log each sync+ #+ # The processor only invokes the helper for CreditCard and Loan accountable+ # types. Depository and Investment balances are passed through unchanged.setup do- @redbark_account = redbark_accounts(:savings_account)- @family = @redbark_account.redbark_item.family-- @account = @family.accounts.create!(- name: "Test Account",- balance: 1000,- currency: "AUD",- accountable: Depository.new- )-- @redbark_account.ensure_account_provider!(@account)- @redbark_account.reload+ @redbark_item = redbark_items(:one)+ @family = @redbark_item.family+ # Set explicitly, as the pre-fix tests did: `families.currency` defaults to+ # USD, so reading it from the fixture family would not give AUD.+ @currency = "AUD"endtest "processor initializes with redbark_account" do- processor = RedbarkAccount::Processor.new(@redbark_account)+ processor = RedbarkAccount::Processor.new(@redbark_item.redbark_accounts.first)assert_not_nil processorend+ # [Control] Depository — non-liability type passes through regardless of provider.+ test "processor passes through Depository balance regardless of provider" do+ account, ra = link(Depository, provider: "plaid", balance: "15000")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("15000"), account.reload.balance++ account, ra = link(Depository, provider: "fiskil", balance: "15000")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("15000"), account.reload.balance+ end++ # [Control] Investment — non-liability type passes through regardless of+ # provider. Uses a negative balance as a discriminating value so it would be+ # caught if the processor were mutated to also flip Investment.+ test "processor passes through Investment balance regardless of provider" do+ account, ra = link(Investment, provider: "plaid", balance: "-10.00")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("-10.00"), account.reload.balance++ account, ra = link(Investment, provider: "fiskil", balance: "-10.00")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("-10.00"), account.reload.balance+ end++ # [Nil guard] A nil current_balance leaves the account untouched (existing+ # behaviour; must be preserved by the fix so a new Plaid-synced liability+ # account can't be clobbered to zero before its first successful balance+ # fetch).+ test "processor skips update when current_balance is nil" do+ account, ra = link(CreditCard, provider: "plaid", balance: nil)+ # A non-zero starting balance, so a write of 0 would show.+ account.update_columns(balance: 1234)++ assert_no_difference -> { account.entries.where(entryable_type: "Valuation").count } do+ RedbarkAccount::Processor.new(ra).process+ end+ assert_equal BigDecimal("1234"), account.reload.balance+ end+test "processor skips processing when no linked account" do- @redbark_account.account_provider&.destroy- @redbark_account.reload+ _, ra = link(Depository, provider: "fiskil", balance: "100")+ ra.account_provider.destroy+ ra.reload++ assert_nothing_raised { RedbarkAccount::Processor.new(ra).process }+ end++ # [Positive — Plaid] Plaid-sourced credit card: +19902.38 arrives as the+ # amount owed (Plaid convention). Stored as a positive amount.+ test "processor stores Plaid-sourced credit card balance as a positive amount owed" do+ card, ra = link(CreditCard, provider: "plaid", balance: "19902.38")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("19902.38"), card.reload.balance+ end++ # [Positive — Plaid-loan parity] The same Plaid passthrough applies to+ # Loan accounts (Plaid also documents loans the way it documents credit+ # cards; if Redbark ever routes a US loan through Plaid the correct+ # behaviour is to store it as a positive amount owed rather than flip it).+ test "processor stores Plaid-sourced loan balance as a positive amount owed" do+ loan, ra = link(Loan, provider: "plaid", balance: "5000.00")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("5000.00"), loan.reload.balance+ end- processor = RedbarkAccount::Processor.new(@redbark_account)- assert_nothing_raised { processor.process }+ # [Overpaid Plaid credit] An overpaid Plaid credit card arrives as a+ # NEGATIVE current_balance (credit balance for the cardholder). Stored as a+ # negative (a credit) — NOT abs()'d, which would flip the sign and misstate+ # it as a liability. This assertion kills the `balance = balance.abs` mutant:+ # abs would store 250.00 instead of -250.00.+ test "processor stores an overpaid Plaid credit card as a negative (credit), not abs()'d" do+ card, ra = link(CreditCard, provider: "plaid", balance: "-250.00")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("-250.00"), card.reload.balanceend- test "processor updates account balance" do- @redbark_account.update!(current_balance: 15000)+ # [Self-heal] A manual correction to a Plaid card sticks through a+ # subsequent sync (each sync writes the provider value back). The bug in+ # #3747 re-applied the inversion on every sync, reverting the correction.+ test "manual correction on a Plaid credit card sticks through the next sync" do+ card, ra = link(CreditCard, provider: "plaid", balance: "549.51")+ RedbarkAccount::Processor.new(ra).process+ card.reload.update!(balance: BigDecimal("549.51"))+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("549.51"), card.reload.balance+ end- RedbarkAccount::Processor.new(@redbark_account).process+ # [Net worth] Syncing a card that owes X must reduce net worth by X (the+ # bug in #3747 moved it by +X, so it overstated the family's net worth by+ # 2X, exactly the amount the card was owing).+ test "syncing a Plaid card that owes X reduces net worth by X" do+ # Net worth is in the family currency. With the fixture family on USD and+ # no AUD->USD rate, the AUD card's balance only counts at 1:1, so measure+ # in the card's own currency rather than lean on that.+ @family.update!(currency: @currency)+ _, ra = link(CreditCard, provider: "plaid", balance: "19902.38")+ before = BalanceSheet.new(@family).net_worth+ RedbarkAccount::Processor.new(ra).process+ after = BalanceSheet.new(@family).net_worth+ assert_equal BigDecimal("-19902.38"), after - before+ end- @account.reload- assert_equal 15000, @account.balance.to_f+ # [Control — CDR card] Fiskil credit card: -842.15 arrives as the amount+ # due (CDR convention). Stored as +842.15. This assertion catches a+ # "simply remove the CDR branch" mutant (QA minor note 2): the mutation+ # would store -842.15.+ test "processor negates a fiskil (CDR) credit card balance so the amount owed is stored positive" do+ card, ra = link(CreditCard, provider: "fiskil", balance: "-842.15")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("842.15"), card.reload.balanceend- test "processor negates balance for credit card accounts" do- credit_account = @family.accounts.create!(- name: "Test Credit Card",- balance: 0,- currency: "AUD",- accountable: CreditCard.new- )- @redbark_account.account_provider&.destroy- @redbark_account.reload- @redbark_account.ensure_account_provider!(credit_account)- @redbark_account.update!(current_balance: -250)+ # [Control — CDR loan] Fiskil home loan: -997672.00 stored as +997672.00.+ test "processor negates a fiskil (CDR) loan balance so the amount owed is stored positive" do+ loan, ra = link(Loan, provider: "fiskil", balance: "-997672.00")+ RedbarkAccount::Processor.new(ra).process+ assert_equal BigDecimal("997672.00"), loan.reload.balance+ end- RedbarkAccount::Processor.new(@redbark_account).process+ # [Unknown provider] An unrecognised provider string keeps the CDR+ # convention and records exactly one DebugLogEntry so support can confirm+ # or correct the convention.+ test "unknown provider keeps CDR negation and records exactly one DebugLogEntry" do+ card, ra = link(CreditCard, provider: "akahu", balance: "-1000.00")+ # also clear any stray entries so the count assertion is meaningful+ DebugLogEntry.where(category: "redbark_sync").delete_all- credit_account.reload- assert_equal 250, credit_account.balance.to_f+ RedbarkAccount::Processor.new(ra).process++ assert_equal BigDecimal("1000.00"), card.reload.balance+ entries = DebugLogEntry.where(category: "redbark_sync")+ assert_equal 1, entries.count,+ "expected exactly one DebugLogEntry for an unrecognised provider, got #{entries.size}"+ entry = entries.first+ assert_includes entry.provider_key.to_s, "akahu"+ assert_match /unrecognised or blank provider/i, entry.message+ assert_equal card, entry.account+ assert_equal ra.account_provider, entry.account_providerend+ # [Unknown provider — blank] A blank/missing provider also records one+ # DebugLogEntry and keeps the CDR convention.+ test "blank provider keeps CDR negation and records exactly one DebugLogEntry" do+ card, ra = link(CreditCard, provider: nil, balance: "-999.99")+ DebugLogEntry.where(category: "redbark_sync").delete_all++ RedbarkAccount::Processor.new(ra).process++ assert_equal BigDecimal("999.99"), card.reload.balance+ assert_equal 1, DebugLogEntry.where(category: "redbark_sync").count+ end++ # [Known — fiskil] A fiskil-synced liability does NOT record any of the+ # new DebugLogEntries (we have high confidence in Fiskil's convention).+ test "fiskil provider does NOT record a DebugLogEntry for a liability" do+ _, ra = link(CreditCard, provider: "fiskil", balance: "-842.15")+ DebugLogEntry.where(category: "redbark_sync").delete_all+ RedbarkAccount::Processor.new(ra).process+ assert_equal 0, DebugLogEntry.where(category: "redbark_sync").count+ end++ # [Known — plaid] A plaid-synced liability does NOT record any of the new+ # DebugLogEntries (the reporter's own confirmation is the evidence).+ test "plaid provider does NOT record a DebugLogEntry for a liability" do+ _, ra = link(CreditCard, provider: "plaid", balance: "12345.67")+ DebugLogEntry.where(category: "redbark_sync").delete_all+ RedbarkAccount::Processor.new(ra).process+ assert_equal 0, DebugLogEntry.where(category: "redbark_sync").count+ end++ # The transaction tests below are carried over from the pre-fix file, set up+ # through `link` instead of the old shared fixture account.test "transactions processor creates entries from raw payload" do- @redbark_account.update!(raw_transactions_payload: [+ account, ra = link(Depository, provider: "fiskil", balance: "100")+ ra.update!(raw_transactions_payload: [{"id" => "tx_001",- "accountId" => @redbark_account.redbark_account_id,+ "accountId" => ra.redbark_account_id,"status" => "posted","date" => Date.current.to_s,"description" => "COFFEE SHOP SYDNEY",@@ -71,22 +212,19 @@ class RedbarkAccount::ProcessorTest < ActiveSupport::TestCase"merchantName" => "Coffee Shop"}])-- result = RedbarkAccount::Transactions::Processor.new(@redbark_account).process-+ result = RedbarkAccount::Transactions::Processor.new(ra).processassert result[:success]assert_equal 1, result[:imported]-- entry = @account.entries.find_by(external_id: "redbark_tx_001", source: "redbark")+ entry = account.entries.find_by(external_id: "redbark_tx_001", source: "redbark")assert_not_nil entry- # Redbark amounts are CDR pre-signed (negative = money out); Sure stores the opposite signassert_equal 4.50, entry.amount.to_fassert_equal "Coffee Shop", entry.nameassert_equal "AUD", entry.currencyendtest "transactions processor stores pending flag in extra metadata" do- @redbark_account.update!(raw_transactions_payload: [+ account, ra = link(Depository, provider: "fiskil", balance: "100")+ ra.update!(raw_transactions_payload: [{"id" => "tx_002","status" => "pending",@@ -97,19 +235,20 @@ class RedbarkAccount::ProcessorTest < ActiveSupport::TestCase}])- RedbarkAccount::Transactions::Processor.new(@redbark_account).process+ RedbarkAccount::Transactions::Processor.new(ra).process- entry = @account.entries.find_by(external_id: "redbark_tx_002", source: "redbark")+ entry = account.entries.find_by(external_id: "redbark_tx_002", source: "redbark")assert_not_nil entryassert_equal true, entry.entryable.extra.dig("redbark", "pending")endtest "transactions processor handles missing transaction id gracefully" do- @redbark_account.update!(raw_transactions_payload: [+ _, ra = link(Depository, provider: "fiskil", balance: "100")+ ra.update!(raw_transactions_payload: [{ "id" => nil, "amount" => "-50.00", "date" => Date.current.to_s }])- result = RedbarkAccount::Transactions::Processor.new(@redbark_account).process+ result = RedbarkAccount::Transactions::Processor.new(ra).processassert result[:success]assert_equal 1, result[:skipped]@@ -117,11 +256,34 @@ class RedbarkAccount::ProcessorTest < ActiveSupport::TestCaseendtest "transactions processor returns empty result when no transactions" do- @redbark_account.update!(raw_transactions_payload: [])+ _, ra = link(Depository, provider: "fiskil", balance: "100")+ ra.update!(raw_transactions_payload: [])- result = RedbarkAccount::Transactions::Processor.new(@redbark_account).process+ result = RedbarkAccount::Transactions::Processor.new(ra).processassert result[:success]assert_equal 0, result[:total]end++ private++ def link(accountable_class, provider:, balance:)+ account = @family.accounts.create!(+ name: "Test #{accountable_class.name} (#{provider.inspect}) #{SecureRandom.hex(3)}",+ balance: 0,+ currency: @currency,+ accountable: accountable_class.new+ )+ redbark_account = @redbark_item.redbark_accounts.create!(+ redbark_account_id: "rb_test_#{SecureRandom.hex(4)}",+ name: account.name,+ currency: @currency,+ provider: provider,+ account_type: accountable_class.name.underscore,+ current_balance: balance.nil? ? nil : BigDecimal(balance)+ )+ redbark_account.ensure_account_provider!(account)+ redbark_account.reload+ [ account, redbark_account ]+ endend