Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
21.2 KB
Raw Blame
require "test_helper"

class PlaidAccount::ProcessorTest < ActiveSupport::TestCase
  setup do
    @plaid_account = plaid_accounts(:one)
  end

  test "processes new account and assigns attributes" do
    Account.destroy_all # Clear out internal accounts so we start fresh

    expect_default_subprocessor_calls

    @plaid_account.update!(
      plaid_id: "test_plaid_id",
      plaid_type: "depository",
      plaid_subtype: "checking",
      current_balance: 1000,
      available_balance: 1000,
      currency: "USD",
      name: "Test Plaid Account",
      mask: "1234"
    )

    assert_difference "Account.count" do
      PlaidAccount::Processor.new(@plaid_account).process
    end

    @plaid_account.reload

    account = Account.order(created_at: :desc).first
    assert_equal "Test Plaid Account", account.name
    assert_equal "checking", account.subtype
    assert_equal 1000, account.balance
    assert_equal 1000, account.cash_balance
    assert_equal "USD", account.currency
    assert_equal "Depository", account.accountable_type
    assert_equal "checking", account.subtype

    # Verify AccountProvider was created
    assert account.linked?
    assert_equal 1, account.account_providers.count
    assert_equal @plaid_account.id, account.account_providers.first.provider_id
    assert_equal "PlaidAccount", account.account_providers.first.provider_type
  end

  test "a new account inherits the owner of the item that produced it" do
    # Accounts are created inside the sync job, where Current.user is nil. If
    # the owner were left to Account#assign_default_owner it would fall back to
    # the family's first admin, quietly taking a member's own connection away
    # from them (issue #3579).
    Account.destroy_all
    member = users(:family_member)
    @plaid_account.plaid_item.update!(owner: member)

    expect_default_subprocessor_calls

    Current.reset

    assert_difference "Account.count" do
      PlaidAccount::Processor.new(@plaid_account).process
    end

    assert_equal member, Account.order(created_at: :desc).first.owner
  end

  test "processing is idempotent with updates and enrichments" do
    expect_default_subprocessor_calls

    assert_equal "Plaid Depository Account", @plaid_account.current_account.name
    assert_equal "checking", @plaid_account.current_account.subtype

    @plaid_account.current_account.update!(
      name: "User updated name",
      balance: 2000 # User cannot override balance.  This will be overridden by the processor on next processing
    )

    @plaid_account.current_account.accountable.update!(subtype: "savings")

    @plaid_account.current_account.lock_attr!(:name)
    @plaid_account.current_account.accountable.lock_attr!(:subtype)
    @plaid_account.current_account.lock_attr!(:balance) # Even if balance somehow becomes locked, Plaid ignores it and overrides it

    assert_no_difference "Account.count" do
      PlaidAccount::Processor.new(@plaid_account).process
    end

    @plaid_account.reload

    assert_equal "User updated name", @plaid_account.current_account.name
    assert_equal "savings", @plaid_account.current_account.subtype
    assert_equal @plaid_account.current_balance, @plaid_account.current_account.balance # Overriden by processor
  end

  test "account processing failure halts further processing" do
    Account.any_instance.stubs(:save!).raises(StandardError.new("Test error"))

    PlaidAccount::Transactions::Processor.any_instance.expects(:process).never
    PlaidAccount::Investments::TransactionsProcessor.any_instance.expects(:process).never
    PlaidAccount::Investments::HoldingsProcessor.any_instance.expects(:process).never

    expect_no_investment_balance_calculator_calls
    expect_no_liability_processor_calls

    assert_raises(StandardError) do
      PlaidAccount::Processor.new(@plaid_account).process
    end
  end

  test "product processing failure reports exception and continues processing" do
    PlaidAccount::Transactions::Processor.any_instance.stubs(:process).raises(StandardError.new("Test error"))

    # Subsequent product processors still run
    expect_investment_product_processor_calls

    assert_nothing_raised do
      PlaidAccount::Processor.new(@plaid_account).process
    end
  end

  test "calculates balance using BalanceCalculator for investment accounts" do
    @plaid_account.update!(plaid_type: "investment")

    # Balance is computed once and used for both account.balance and the anchor
    PlaidAccount::Investments::BalanceCalculator.any_instance.expects(:balance).returns(1000).once
    PlaidAccount::Investments::BalanceCalculator.any_instance.expects(:cash_balance).returns(1000).once

    PlaidAccount::Processor.new(@plaid_account).process

    # Verify that the balance was set correctly
    account = @plaid_account.current_account
    assert_equal 1000, account.balance
    assert_equal 1000, account.cash_balance

    # Verify current balance anchor was created with correct value
    current_anchor = account.valuations.current_anchor.first
    assert_not_nil current_anchor
    assert_equal 1000, current_anchor.entry.amount
  end

  test "processes credit liability data" do
    expect_investment_product_processor_calls
    expect_no_investment_balance_calculator_calls
    expect_depository_product_processor_calls

    @plaid_account.update!(plaid_type: "credit", plaid_subtype: "credit card")

    PlaidAccount::Liabilities::CreditProcessor.any_instance.expects(:process).once
    PlaidAccount::Liabilities::MortgageProcessor.any_instance.expects(:process).never
    PlaidAccount::Liabilities::StudentLoanProcessor.any_instance.expects(:process).never

    PlaidAccount::Processor.new(@plaid_account).process
  end

  test "processes credit liability data for non-credit-card subtypes" do
    # Plaid reports PayPal Credit as credit/paypal. Dispatching only on
    # ["credit", "credit card"] left these accounts with a stored liabilities
    # payload but no minimum_payment or apr.
    expect_investment_product_processor_calls
    expect_no_investment_balance_calculator_calls
    expect_depository_product_processor_calls

    @plaid_account.update!(plaid_type: "credit", plaid_subtype: "paypal")

    PlaidAccount::Liabilities::CreditProcessor.any_instance.expects(:process).once
    PlaidAccount::Liabilities::MortgageProcessor.any_instance.expects(:process).never
    PlaidAccount::Liabilities::StudentLoanProcessor.any_instance.expects(:process).never

    PlaidAccount::Processor.new(@plaid_account).process
  end

  test "processes mortgage liability data" do
    expect_investment_product_processor_calls
    expect_no_investment_balance_calculator_calls
    expect_depository_product_processor_calls

    @plaid_account.update!(plaid_type: "loan", plaid_subtype: "mortgage")

    PlaidAccount::Liabilities::CreditProcessor.any_instance.expects(:process).never
    PlaidAccount::Liabilities::MortgageProcessor.any_instance.expects(:process).once
    PlaidAccount::Liabilities::StudentLoanProcessor.any_instance.expects(:process).never

    PlaidAccount::Processor.new(@plaid_account).process
  end

  # The loan processors date a rate change, so they are given the sync's date
  # rather than reading the clock.
  test "the sync date reaches the liability processor" do
    expect_investment_product_processor_calls
    expect_no_investment_balance_calculator_calls
    expect_depository_product_processor_calls

    @plaid_account.update!(plaid_type: "loan", plaid_subtype: "mortgage")
    date = Date.new(2026, 1, 15)
    mortgage = mock("mortgage_processor")
    mortgage.expects(:process).once

    PlaidAccount::Liabilities::MortgageProcessor.expects(:new).with(@plaid_account, as_of: date).returns(mortgage)

    PlaidAccount::Processor.new(@plaid_account, as_of: date).process
  end

  test "the sync date reaches the student loan processor" do
    expect_investment_product_processor_calls
    expect_no_investment_balance_calculator_calls
    expect_depository_product_processor_calls

    @plaid_account.update!(plaid_type: "loan", plaid_subtype: "student")
    date = Date.new(2026, 1, 15)
    student_loan = mock("student_loan_processor")
    student_loan.expects(:process).once

    PlaidAccount::Liabilities::StudentLoanProcessor.expects(:new).with(@plaid_account, as_of: date).returns(student_loan)

    PlaidAccount::Processor.new(@plaid_account, as_of: date).process
  end

  test "processes student loan liability data" do
    expect_investment_product_processor_calls
    expect_no_investment_balance_calculator_calls
    expect_depository_product_processor_calls

    @plaid_account.update!(plaid_type: "loan", plaid_subtype: "student")

    PlaidAccount::Liabilities::CreditProcessor.any_instance.expects(:process).never
    PlaidAccount::Liabilities::MortgageProcessor.any_instance.expects(:process).never
    PlaidAccount::Liabilities::StudentLoanProcessor.any_instance.expects(:process).once

    PlaidAccount::Processor.new(@plaid_account).process
  end

  test "creates current balance anchor when processing account" do
    expect_default_subprocessor_calls

    # Clear out accounts to start fresh
    Account.destroy_all

    @plaid_account.update!(
      plaid_id: "test_plaid_id",
      plaid_type: "depository",
      plaid_subtype: "checking",
      current_balance: 1500,
      available_balance: 1500,
      currency: "USD",
      name: "Test Account with Anchor",
      mask: "1234"
    )

    assert_difference "Account.count", 1 do
      assert_difference "Entry.count", 1 do
        assert_difference "Valuation.count", 1 do
          PlaidAccount::Processor.new(@plaid_account).process
        end
      end
    end

    account = Account.order(created_at: :desc).first
    assert_equal 1500, account.balance

    # Verify current balance anchor was created
    current_anchor = account.valuations.current_anchor.first
    assert_not_nil current_anchor
    assert_equal "current_anchor", current_anchor.kind
    assert_equal 1500, current_anchor.entry.amount
    assert_equal Date.current, current_anchor.entry.date
    assert_equal "Current balance", current_anchor.entry.name
  end

  test "an investment anchor is dated on the holdings' price date, not today" do
    expect_investment_product_processor_calls
    expect_depository_product_processor_calls
    expect_no_liability_processor_calls
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)

    price_date = Date.current - 1
    @plaid_account.update!(
      plaid_type: "investment",
      raw_holdings_payload: { "holdings" => [
        { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => price_date.to_s },
        { "security_id" => "sec_2", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => (price_date - 3).to_s }
      ] }
    )

    PlaidAccount::Processor.new(@plaid_account).process

    account = @plaid_account.current_account
    current_anchor = account.valuations.current_anchor.first
    assert_equal price_date, current_anchor.entry.date, "the newest price date the holdings carry"
    assert_equal 1000, current_anchor.entry.amount
    assert_equal 1000, account.balance
    assert_equal 100, account.cash_balance
  end

  test "one holding dated ahead of today does not pull the anchor off the others' date" do
    expect_investment_product_processor_calls
    expect_depository_product_processor_calls
    expect_no_liability_processor_calls
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)

    price_date = Date.current - 1
    @plaid_account.update!(
      plaid_type: "investment",
      raw_holdings_payload: { "holdings" => [
        { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => price_date.to_s },
        { "security_id" => "sec_2", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => (Date.current + 1).to_s }
      ] }
    )

    PlaidAccount::Processor.new(@plaid_account).process

    current_anchor = @plaid_account.current_account.valuations.current_anchor.first
    assert_equal price_date, current_anchor.entry.date
  end

  test "an investment anchor falls back to today without a usable price date" do
    expect_investment_product_processor_calls
    expect_depository_product_processor_calls
    expect_no_liability_processor_calls
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)

    @plaid_account.update!(
      plaid_type: "investment",
      raw_holdings_payload: { "holdings" => [
        { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => nil },
        { "security_id" => "sec_2", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => "not a date" },
        { "security_id" => "sec_3", "quantity" => "1", "institution_price" => "10", "institution_price_as_of" => (Date.current + 1).to_s }
      ] }
    )

    PlaidAccount::Processor.new(@plaid_account).process

    current_anchor = @plaid_account.current_account.valuations.current_anchor.first
    assert_equal Date.current, current_anchor.entry.date
  end

  test "an investment's holdings are written on its balance anchor's date" do
    PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)
    PlaidAccount::Transactions::Processor.any_instance.stubs(:process)
    expect_no_liability_processor_calls
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)

    snapshot_date = Date.current - 1
    securities_by_plaid_id = {
      "a" => securities(:aapl),
      "b" => securities(:msft),
      "c" => Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US"),
      "e" => Security.create!(ticker: "AMZN", name: "Amazon", exchange_operating_mic: "XNAS", country_code: "US")
    }
    securities_by_plaid_id.each do |plaid_security_id, security|
      PlaidAccount::Investments::SecurityResolver.any_instance.stubs(:resolve)
        .with(plaid_security_id: plaid_security_id)
        .returns(OpenStruct.new(security: security))
    end

    @plaid_account.update!(
      plaid_type: "investment",
      raw_holdings_payload: { "holdings" => [
        { "security_id" => "a", "quantity" => "10", "institution_price" => "90", "iso_currency_code" => "USD", "institution_price_as_of" => snapshot_date.to_s },
        { "security_id" => "b", "quantity" => "5", "institution_price" => "20", "iso_currency_code" => "USD", "institution_price_as_of" => (snapshot_date - 3).to_s },
        { "security_id" => "c", "quantity" => "2", "institution_price" => "30", "iso_currency_code" => "USD", "institution_price_as_of" => (Date.current + 1).to_s },
        { "security_id" => "e", "quantity" => "1", "institution_price" => "40", "iso_currency_code" => "USD" }
      ] }
    )

    PlaidAccount::Processor.new(@plaid_account).process

    account = @plaid_account.current_account
    anchor_date = account.valuations.current_anchor.first.entry.date
    assert_equal snapshot_date, anchor_date
    assert_equal securities_by_plaid_id.values.map(&:id).sort, account.holdings.pluck(:security_id).sort
    assert_equal [ anchor_date ], account.holdings.distinct.pluck(:date)
  end

  test "the anchor and the holdings both take the account's holdings snapshot date" do
    PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)
    PlaidAccount::Transactions::Processor.any_instance.stubs(:process)
    expect_no_liability_processor_calls
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)
    PlaidAccount::Investments::SecurityResolver.any_instance.stubs(:resolve).returns(OpenStruct.new(security: securities(:aapl)))

    @plaid_account.update!(
      plaid_type: "investment",
      raw_holdings_payload: { "holdings" => [
        { "security_id" => "a", "quantity" => "10", "institution_price" => "90", "iso_currency_code" => "USD", "institution_price_as_of" => (Date.current - 1).to_s }
      ] }
    )
    # A date no rule over this payload would produce, so both readers can
    # only arrive at it through the one method.
    snapshot_date = Date.current - 7
    @plaid_account.stubs(:holdings_snapshot_date).returns(snapshot_date)

    PlaidAccount::Processor.new(@plaid_account).process

    account = @plaid_account.current_account
    assert_equal snapshot_date, account.valuations.current_anchor.first.entry.date
    assert_equal [ snapshot_date ], account.holdings.pluck(:date)
  end

  test "an investment snapshot dated behind the anchor is recorded on its own date and leaves the anchor alone" do
    PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)
    PlaidAccount::Investments::HoldingsProcessor.any_instance.stubs(:process)
    PlaidAccount::Transactions::Processor.any_instance.stubs(:process)
    expect_no_liability_processor_calls
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)

    @plaid_account.update!(
      plaid_type: "investment",
      raw_holdings_payload: { "holdings" => [ { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "90", "institution_price_as_of" => Date.current.to_s } ] }
    )
    PlaidAccount::Processor.new(@plaid_account).process
    account = @plaid_account.current_account
    anchor = account.valuations.current_anchor.first

    # The next snapshot is dated behind the anchor, carries an older total,
    # and reports a different currency.
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(900)
    PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(50)
    @plaid_account.update!(
      currency: "EUR",
      raw_holdings_payload: { "holdings" => [ { "security_id" => "sec_1", "quantity" => "10", "institution_price" => "85", "institution_price_as_of" => (Date.current - 1).to_s } ] }
    )

    assert_difference "account.valuations.reconciliation.count", 1 do
      PlaidAccount::Processor.new(@plaid_account).process
    end

    anchor.reload
    account.reload
    assert_equal Date.current, anchor.entry.date
    assert_equal 1000, anchor.entry.amount, "the anchor still describes now"
    assert_equal 1000, account.balance
    assert_equal 100, account.cash_balance
    assert_equal "USD", account.currency, "the cached figures keep the denomination they were written in"
    historical = account.valuations.reconciliation.joins(:entry).find_by(entries: { date: Date.current - 1 })
    assert_equal 900, historical.entry.amount
  end

  test "updates existing current balance anchor when reprocessing" do
    # First process creates the account and anchor
    expect_default_subprocessor_calls
    PlaidAccount::Processor.new(@plaid_account).process

    account = @plaid_account.current_account
    original_anchor = account.valuations.current_anchor.first
    assert_not_nil original_anchor
    original_anchor_id = original_anchor.id
    original_entry_id = original_anchor.entry.id
    original_balance = original_anchor.entry.amount

    # Update the plaid account balance
    @plaid_account.update!(current_balance: 2500)

    # Expect subprocessor calls again for the second processing
    expect_default_subprocessor_calls

    # Reprocess should update the existing anchor
    assert_no_difference "Valuation.count" do
      assert_no_difference "Entry.count" do
        PlaidAccount::Processor.new(@plaid_account).process
      end
    end

    # Verify the anchor was updated
    original_anchor.reload
    assert_equal original_anchor_id, original_anchor.id
    assert_equal original_entry_id, original_anchor.entry.id
    assert_equal 2500, original_anchor.entry.amount
    assert_not_equal original_balance, original_anchor.entry.amount
  end

  private
    def expect_investment_product_processor_calls
      PlaidAccount::Investments::TransactionsProcessor.any_instance.expects(:process).once
      PlaidAccount::Investments::HoldingsProcessor.any_instance.expects(:process).once
    end

    def expect_depository_product_processor_calls
      PlaidAccount::Transactions::Processor.any_instance.expects(:process).once
    end

    def expect_no_investment_balance_calculator_calls
      PlaidAccount::Investments::BalanceCalculator.any_instance.expects(:balance).never
      PlaidAccount::Investments::BalanceCalculator.any_instance.expects(:cash_balance).never
    end

    def expect_no_liability_processor_calls
      PlaidAccount::Liabilities::CreditProcessor.any_instance.expects(:process).never
      PlaidAccount::Liabilities::MortgageProcessor.any_instance.expects(:process).never
      PlaidAccount::Liabilities::StudentLoanProcessor.any_instance.expects(:process).never
    end

    def expect_default_subprocessor_calls
      expect_depository_product_processor_calls
      expect_investment_product_processor_calls
      expect_no_investment_balance_calculator_calls
      expect_no_liability_processor_calls
    end
end