Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
18.9 KB
Raw Blame
# frozen_string_literal: true

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_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"
  end

  test "processor initializes with redbark_account" do
    processor = RedbarkAccount::Processor.new(@redbark_item.redbark_accounts.first)
    assert_not_nil processor
  end

  # [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
    _, 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

  # [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.balance
  end

  # [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

  # [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

  # [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.balance
  end

  # A sync carries the card's published purchase rate onto
  # a blank APR, so the processor must run the card details step.
  test "processor fills a blank credit card APR from this sync's account details" do
    card, ra = link(CreditCard, provider: "fiskil", balance: "-842.15")
    as_of = Date.new(2026, 11, 20)
    ra.update!(
      raw_account_details_payload: { "lendingRates" => [ { "rateType" => "PURCHASE", "rate" => "0.1999" } ] },
      account_details_fetched_at: as_of.in_time_zone
    )

    RedbarkAccount::Processor.new(ra.reload, as_of: as_of).process

    assert_equal BigDecimal("19.99"), card.reload.accountable.apr
  end

  test "a card details failure does not skip the sync broadcast" do
    card, ra = link(CreditCard, provider: "fiskil", balance: "-842.15")
    as_of = Date.new(2026, 11, 20)
    ra.update!(raw_account_details_payload: [ "unexpected" ], account_details_fetched_at: as_of.in_time_zone)
    Account.any_instance.expects(:broadcast_sync_complete).once

    assert_nothing_raised { RedbarkAccount::Processor.new(ra.reload, as_of: as_of).process }
    assert_nil card.reload.accountable.apr
  end

  # [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

  # [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

    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_provider
  end

  # [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
    account, ra = link(Depository, provider: "fiskil", balance: "100")
    ra.update!(raw_transactions_payload: [
      {
        "id" => "tx_001",
        "accountId" => ra.redbark_account_id,
        "status" => "posted",
        "date" => Date.current.to_s,
        "description" => "COFFEE SHOP SYDNEY",
        "amount" => "-4.50",
        "direction" => "debit",
        "merchantName" => "Coffee Shop"
      }
    ])
    result = RedbarkAccount::Transactions::Processor.new(ra).process
    assert result[:success]
    assert_equal 1, result[:imported]
    entry = account.entries.find_by(external_id: "redbark_tx_001", source: "redbark")
    assert_not_nil entry
    assert_equal 4.50, entry.amount.to_f
    assert_equal "Coffee Shop", entry.name
    assert_equal "AUD", entry.currency
  end

  test "transactions processor stores pending flag in extra metadata" do
    account, ra = link(Depository, provider: "fiskil", balance: "100")
    ra.update!(raw_transactions_payload: [
      {
        "id" => "tx_002",
        "status" => "pending",
        "date" => Date.current.to_s,
        "description" => "PENDING PURCHASE",
        "amount" => "-10.00",
        "direction" => "debit"
      }
    ])

    RedbarkAccount::Transactions::Processor.new(ra).process

    entry = account.entries.find_by(external_id: "redbark_tx_002", source: "redbark")
    assert_not_nil entry
    assert_equal true, entry.entryable.extra.dig("redbark", "pending")
  end

  test "transactions processor handles missing transaction id gracefully" do
    _, 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(ra).process

    assert result[:success]
    assert_equal 1, result[:skipped]
    assert_equal 0, result[:failed]
  end

  test "transactions processor applies the matched Sure category" do
    @family.categories.bootstrap!
    account, ra = link(Depository, provider: "fiskil", balance: "100")

    ra.update!(raw_transactions_payload: [
      {
        "id" => "tx_cat_1",
        "status" => "posted",
        "date" => Date.current.to_s,
        "description" => "WOOLWORTHS SYDNEY",
        "amount" => "-45.00",
        "direction" => "debit",
        "merchantName" => "Woolworths",
        "category" => "FOOD_AND_DRINK"
      }
    ])

    RedbarkAccount::Transactions::Processor.new(ra).process

    entry = account.entries.find_by(external_id: "redbark_tx_cat_1", source: "redbark")
    assert_equal "Food & Drink", entry.transaction.category&.name
  end

  test "transactions processor falls back to merchant_category_code when category is unmapped" do
    @family.categories.bootstrap!
    account, ra = link(Depository, provider: "fiskil", balance: "100")

    ra.update!(raw_transactions_payload: [
      {
        "id" => "tx_cat_mcc",
        "status" => "posted",
        "date" => Date.current.to_s,
        "description" => "WOOLWORTHS SYDNEY",
        "amount" => "-45.00",
        "direction" => "debit",
        "merchantName" => "Woolworths",
        "category" => "MERCHANDISE", # intentionally unmapped by category code alone
        "merchantCategoryCode" => "5411" # supermarkets -> Groceries
      }
    ])

    RedbarkAccount::Transactions::Processor.new(ra).process

    entry = account.entries.find_by(external_id: "redbark_tx_cat_mcc", source: "redbark")
    assert_equal "Groceries", entry.transaction.category&.name
  end

  # The PR claims a category the user set or locked survives a re-import. enrich_attribute
  # respects locked_attributes, so a re-sync of the same transaction must leave it alone.
  test "transactions processor does not overwrite a locked category on re-import" do
    @family.categories.bootstrap!
    account, ra = link(Depository, provider: "fiskil", balance: "100")

    payload = [
      {
        "id" => "tx_cat_locked",
        "status" => "posted",
        "date" => Date.current.to_s,
        "description" => "WOOLWORTHS SYDNEY",
        "amount" => "-45.00",
        "direction" => "debit",
        "merchant" => "Woolworths",
        "category" => "FOOD_AND_DRINK"
      }
    ]

    ra.update!(raw_transactions_payload: payload)
    RedbarkAccount::Transactions::Processor.new(ra).process

    entry = account.entries.find_by(external_id: "redbark_tx_cat_locked", source: "redbark")
    chosen = @family.categories.find_by(name: "Entertainment")
    entry.transaction.update!(category: chosen)
    entry.transaction.lock_attr!(:category_id)

    ra.update!(raw_transactions_payload: payload)
    RedbarkAccount::Transactions::Processor.new(ra).process

    assert_equal "Entertainment", entry.transaction.reload.category&.name,
      "a locked category must survive a Redbark re-import"
  end

  test "transactions processor skips category matching when the account has the matcher switched off" do
    @family.categories.bootstrap!
    account, ra = link(Depository, provider: "fiskil", balance: "100")
    account.update!(enable_category_matcher: false)

    ra.update!(raw_transactions_payload: [
      {
        "id" => "tx_cat_2",
        "status" => "posted",
        "date" => Date.current.to_s,
        "description" => "WOOLWORTHS SYDNEY",
        "amount" => "-45.00",
        "direction" => "debit",
        "merchantName" => "Woolworths",
        "category" => "FOOD_AND_DRINK"
      }
    ])

    RedbarkAccount::Transactions::Processor.new(ra).process

    entry = account.entries.find_by(external_id: "redbark_tx_cat_2", source: "redbark")
    assert_nil entry.transaction.category_id
    # Still imported, still carries the raw category - only the auto-category is withheld.
    assert_equal "FOOD_AND_DRINK", entry.transaction.extra.dig("redbark", "category")
  end

  test "transactions processor returns empty result when no transactions" do
    _, ra = link(Depository, provider: "fiskil", balance: "100")
    ra.update!(raw_transactions_payload: [])

    result = RedbarkAccount::Transactions::Processor.new(ra).process

    assert result[:success]
    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:)
      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 ]
    end
end