Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
19.2 KB
Raw Blame
require "test_helper"

class RedbarkItem::ImporterTest < ActiveSupport::TestCase
  setup do
    @redbark_item = redbark_items(:one)
    @importer = RedbarkItem::Importer.new(@redbark_item, redbark_provider: nil)
  end

  # Row 7: account details are the one thing in the sync a loan's rate
  # depends on, and the one thing a user can live without. A failure there must
  # not cost them balances or transactions.
  test "a failing account details fetch leaves the payload alone and does not raise" do
    redbark_account = redbark_accounts(:savings_account)
    family = redbark_account.redbark_item.family
    account = family.accounts.create!(
      name: "Mortgage", balance: 400_000, currency: "AUD",
      accountable: Loan.new(rate_type: "variable", interest_rate: 6.25)
    )
    redbark_account.ensure_account_provider!(account)
    redbark_account.update!(raw_account_details_payload: { "lendingRate" => "0.0625" })

    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.stubs(:get_account_details).raises(Provider::Redbark::Error.new("boom", :server_error))
    importer = RedbarkItem::Importer.new(redbark_account.redbark_item, redbark_provider: provider)

    assert_nothing_raised do
      importer.send(:import_account_details, [ redbark_account.reload ])
    end

    assert_equal({ "lendingRate" => "0.0625" }, redbark_account.reload.raw_account_details_payload,
                 "a failed fetch overwrote the details the last good sync stored")
  end

  # The stamp is the sync's clock, injected, not the importer's own reading of
  # it. Both phases of a sync have to agree on which day the snapshot belongs
  # to; see RedbarkItem::SyncerTest for why they must not read the clock twice.
  test "the injected clock stamps the snapshot, not the wall clock" do
    redbark_account = redbark_accounts(:savings_account)
    family = redbark_account.redbark_item.family
    account = family.accounts.create!(
      name: "Mortgage", balance: 400_000, currency: "AUD",
      accountable: Loan.new(rate_type: "variable", interest_rate: 6.25)
    )
    redbark_account.ensure_account_provider!(account)

    injected = Time.utc(2026, 9, 21, 23, 59, 30)
    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.stubs(:get_account_details).returns([
      { accountId: redbark_account.redbark_account_id, lendingRate: "0.0675" }
    ])
    importer = RedbarkItem::Importer.new(
      redbark_account.redbark_item, redbark_provider: provider, fetched_at: injected
    )

    travel_to Time.utc(2026, 9, 22, 0, 0, 30) do
      importer.send(:import_account_details, [ redbark_account.reload ])
    end

    assert_equal injected, redbark_account.reload.account_details_fetched_at.utc,
                 "the importer stamped its own reading of the clock instead of the sync's"
  end

  # The batch is rejected whole when one id is stale or of the wrong category,
  # so one bad account must not cost every other loan its rate. Mirrors
  # fetch_balances_with_fallback.
  #
  # Two DISTINCT accounts, because the fallback only engages for a batch of
  # more than one: with a single id there is nothing to demote to.
  test "a rejected batch falls back to one call per account" do
    first = redbark_accounts(:savings_account)
    item = first.redbark_item
    family = item.family
    second = item.redbark_accounts.create!(
      redbark_account_id: "rb_acc_loan_2", name: "Second loan", currency: "AUD"
    )

    [ first, second ].each_with_index do |redbark_account, index|
      account = family.accounts.create!(
        name: "Mortgage #{index}", balance: 400_000, currency: "AUD",
        accountable: Loan.new(rate_type: "variable", interest_rate: 6.25)
      )
      redbark_account.ensure_account_provider!(account)
    end

    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details)
            .with(account_ids: [ first.redbark_account_id, second.redbark_account_id ])
            .raises(Provider::Redbark::Error.new("stale id", :not_found))
    provider.expects(:get_account_details)
            .with(account_ids: [ first.redbark_account_id ])
            .returns([ { accountId: first.redbark_account_id, lendingRate: "0.0675" } ])
    provider.expects(:get_account_details)
            .with(account_ids: [ second.redbark_account_id ])
            .returns([])

    importer = RedbarkItem::Importer.new(item, redbark_provider: provider)
    importer.send(:import_account_details, [ first.reload, second.reload ])

    assert_equal "0.0675", first.reload.raw_account_details_payload["lendingRate"],
                 "the account the retry could serve never got its details stored"
    assert_not_nil first.account_details_fetched_at, "a stored refresh was not stamped"
    assert_nil second.reload.raw_account_details_payload,
               "an account the retry could not serve was written anyway"
  end

  # Only loans and credit cards: every other account type would cost a request
  # per sync for a field nothing reads.
  test "account details are not fetched when no linked account is a loan or credit card" do
    redbark_account = redbark_accounts(:savings_account)
    family = redbark_account.redbark_item.family
    account = family.accounts.create!(
      name: "Everyday", balance: 100, currency: "AUD", accountable: Depository.new
    )
    redbark_account.ensure_account_provider!(account)

    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details).never
    importer = RedbarkItem::Importer.new(redbark_account.redbark_item, redbark_provider: provider)

    importer.send(:import_account_details, [ redbark_account.reload ])
  end

  # A card's APR comes from the same endpoint.
  test "a credit card's account details are fetched and stamped" do
    redbark_account = redbark_accounts(:savings_account)
    family = redbark_account.redbark_item.family
    account = family.accounts.create!(
      name: "Credit card", balance: 100, currency: "AUD", accountable: CreditCard.new
    )
    redbark_account.ensure_account_provider!(account)

    injected = Time.utc(2026, 11, 20, 9, 0, 0)
    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details)
            .with(account_ids: [ redbark_account.redbark_account_id ])
            .returns([ { accountId: redbark_account.redbark_account_id, lendingRates: [ { rateType: "PURCHASE", rate: "0.1999" } ] } ])
    importer = RedbarkItem::Importer.new(
      redbark_account.redbark_item, redbark_provider: provider, fetched_at: injected
    )

    importer.send(:import_account_details, [ redbark_account.reload ])

    redbark_account.reload
    assert_equal "0.1999", redbark_account.raw_account_details_payload.dig("lendingRates", 0, "rate"),
                 "a credit card's details were not stored"
    assert_equal injected, redbark_account.account_details_fetched_at.utc
  end

  # Cards are fetched in a batch of their own, so a card id the endpoint
  # rejects leaves the loans' single batched call alone.
  test "a rejected card id does not push the loans into per-account retries" do
    loan_ra = redbark_accounts(:savings_account)
    item = loan_ra.redbark_item
    family = item.family
    card_ra = item.redbark_accounts.create!(redbark_account_id: "rb_acc_card_1", name: "Card", currency: "AUD")
    loan_ra.ensure_account_provider!(
      family.accounts.create!(name: "Mortgage", balance: 400_000, currency: "AUD", accountable: Loan.new)
    )
    card_ra.ensure_account_provider!(
      family.accounts.create!(name: "Card", balance: 100, currency: "AUD", accountable: CreditCard.new)
    )

    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details)
            .with(account_ids: [ loan_ra.redbark_account_id ]).once
            .returns([ { accountId: loan_ra.redbark_account_id, lendingRate: "0.0675" } ])
    provider.expects(:get_account_details)
            .with(account_ids: [ card_ra.redbark_account_id ]).once
            .raises(Provider::Redbark::Error.new("stale id", :not_found))

    RedbarkItem::Importer.new(item, redbark_provider: provider)
                         .send(:import_account_details, [ loan_ra.reload, card_ra.reload ])

    assert_equal "0.0675", loan_ra.reload.raw_account_details_payload["lendingRate"]
    assert_nil card_ra.reload.raw_account_details_payload
  end

  test "a card fetched in the last seven days is not fetched again" do
    redbark_account, item = link_card("rb_acc_card_recent")
    now = Time.utc(2026, 11, 20, 9, 0, 0)
    redbark_account.update!(account_details_fetched_at: now - 6.days)

    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details).never

    RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)
                         .send(:import_account_details, [ redbark_account.reload ])
  end

  test "a card is fetched again once seven days have passed" do
    redbark_account, item = link_card("rb_acc_card_stale")
    now = Time.utc(2026, 11, 20, 9, 0, 0)
    redbark_account.update!(account_details_fetched_at: now - 7.days)

    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details).with(account_ids: [ "rb_acc_card_stale" ]).once.returns([])

    RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)
                         .send(:import_account_details, [ redbark_account.reload ])
  end

  test "a failed card fetch is stamped, logged and not a sync error" do
    redbark_account, item = link_card("rb_acc_card_failing")
    now = Time.utc(2026, 11, 20, 9, 0, 0)
    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details).once.raises(Provider::Redbark::Error.new("stale id", :not_found))
    importer = RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)

    assert_difference -> { DebugLogEntry.where(source: RedbarkItem::Importer.name).count }, 1 do
      importer.send(:import_account_details, [ redbark_account.reload ])
      RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now + 1.day)
                           .send(:import_account_details, [ redbark_account.reload ])
    end

    assert_equal now, redbark_account.reload.account_details_fetched_at.utc, "a failed attempt was not stamped"
    assert_nil redbark_account.raw_account_details_payload
    assert importer.send(:stats)["errors"].blank?, "a card fetch failure was registered as a sync error"
  end

  # The stamp is what the card processor reads as "fetched this window", so a
  # failed attempt must not leave an older payload under a fresh stamp.
  test "a failed card fetch clears an old payload so the APR stays blank" do
    redbark_account, item = link_card("rb_acc_card_old_payload")
    now = Time.utc(2026, 11, 20, 9, 0, 0)
    redbark_account.update!(
      raw_account_details_payload: { "lendingRates" => [ { "rateType" => "PURCHASE", "rate" => "0.1999" } ] },
      account_details_fetched_at: now - 30.days
    )
    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details).once.raises(Provider::Redbark::Error.new("boom", :server_error))

    RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)
                         .send(:import_account_details, [ redbark_account.reload ])
    RedbarkAccount::CreditCardDetailsProcessor.new(redbark_account.reload, as_of: now.to_date).process

    assert_nil redbark_account.current_account.accountable.reload.apr,
               "a payload from before the failed fetch filled the APR"
    assert_nil redbark_account.raw_account_details_payload
  end

  test "a card the provider leaves out is stamped so it waits for the window" do
    redbark_account, item = link_card("rb_acc_card_omitted")
    now = Time.utc(2026, 11, 20, 9, 0, 0)
    redbark_account.update!(raw_account_details_payload: { "lendingRates" => [] }, account_details_fetched_at: now - 30.days)
    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details).once.returns([])

    RedbarkItem::Importer.new(item, redbark_provider: provider, fetched_at: now)
                         .send(:import_account_details, [ redbark_account.reload ])

    assert_equal now, redbark_account.reload.account_details_fetched_at.utc
    assert_nil redbark_account.raw_account_details_payload, "an old payload was kept under the new stamp"
  end

  test "a card failure already logged in the window is not logged again" do
    redbark_account, item = link_card("rb_acc_card_repeat")
    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.stubs(:get_account_details).raises(Provider::Redbark::Error.new("stale id", :not_found))

    assert_difference -> { DebugLogEntry.where(source: RedbarkItem::Importer.name).count }, 1 do
      2.times do
        redbark_account.update_columns(account_details_fetched_at: nil)
        RedbarkItem::Importer.new(item, redbark_provider: provider).send(:import_account_details, [ redbark_account.reload ])
      end
    end
  end

  test "a rejected batch of cards and its per-card retries are each logged once" do
    first, item = link_card("rb_acc_card_a")
    second, = link_card("rb_acc_card_b")
    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.stubs(:get_account_details).raises(Provider::Redbark::Error.new("stale id", :not_found))

    assert_difference -> { DebugLogEntry.where(source: RedbarkItem::Importer.name).count }, 3 do
      2.times do
        [ first, second ].each { |redbark_account| redbark_account.update_columns(account_details_fetched_at: nil) }
        RedbarkItem::Importer.new(item, redbark_provider: provider).send(:import_account_details, [ first.reload, second.reload ])
      end
    end
  end

  test "a card whose APR is set or locked is not fetched" do
    with_apr = redbark_accounts(:savings_account)
    item = with_apr.redbark_item
    family = item.family
    locked = item.redbark_accounts.create!(redbark_account_id: "rb_acc_card_2", name: "Locked card", currency: "AUD")
    with_apr.ensure_account_provider!(
      family.accounts.create!(name: "Card", balance: 100, currency: "AUD", accountable: CreditCard.new(apr: 12.5))
    )
    locked_account = family.accounts.create!(name: "Locked card", balance: 100, currency: "AUD", accountable: CreditCard.new)
    locked_account.accountable.lock_attr!(:apr)
    locked.ensure_account_provider!(locked_account)

    provider = mock
    provider.stubs(:list_connections).returns([])
    provider.expects(:get_account_details).never

    RedbarkItem::Importer.new(item, redbark_provider: provider)
                         .send(:import_account_details, [ with_apr.reload, locked.reload ])
  end

  test "merge_transactions keeps posted rows and refreshes by id" do
    existing = [ { "id" => "t1", "status" => "posted", "date" => "2026-07-01", "amount" => "-10.00" } ]
    fresh = [ { "id" => "t1", "status" => "posted", "date" => "2026-07-01", "amount" => "-12.00" } ]

    merged = @importer.send(:merge_transactions, existing, fresh, window_start: Date.new(2026, 6, 1))

    assert_equal 1, merged.size
    assert_equal "-12.00", merged.first["amount"]
  end

  test "merge_transactions prunes pending rows missing from the refetched window" do
    existing = [
      { "id" => "pend_1", "status" => "pending", "date" => "2026-07-10" },
      { "id" => "kept_posted", "status" => "posted", "date" => "2026-07-05" }
    ]
    fresh = [ { "id" => "post_1", "status" => "posted", "date" => "2026-07-10" } ]

    merged = @importer.send(:merge_transactions, existing, fresh, window_start: Date.new(2026, 7, 1))
    ids = merged.map { |t| t["id"] }

    assert_includes ids, "post_1"
    assert_includes ids, "kept_posted"
    assert_not_includes ids, "pend_1"
  end

  test "merge_transactions drops rows dated before the fetch window" do
    existing = [
      { "id" => "old_posted", "status" => "posted", "date" => "2026-05-01" },
      { "id" => "old_pending", "status" => "pending", "date" => "2026-06-15" },
      { "id" => "undated", "status" => "posted" }
    ]
    fresh = [ { "id" => "post_1", "status" => "posted", "date" => "2026-07-10" } ]

    merged = @importer.send(:merge_transactions, existing, fresh, window_start: Date.new(2026, 7, 1))

    assert_equal %w[post_1 undated], merged.map { |t| t["id"] }.sort
  end

  test "merge_transactions keeps everything when no window is given" do
    existing = [ { "id" => "old_posted", "status" => "posted", "date" => "2026-05-01" } ]
    fresh = [ { "id" => "post_1", "status" => "posted", "date" => "2026-07-10" } ]

    merged = @importer.send(:merge_transactions, existing, fresh, window_start: nil)

    assert_equal %w[old_posted post_1], merged.map { |t| t["id"] }.sort
  end

  test "import_transactions fetches from the stored sync_start_date when it's still within the lookback window" do
    redbark_account = redbark_accounts(:savings_account)
    redbark_account.update!(sync_start_date: 6.months.ago.to_date)

    assert_fetches_from(redbark_account, 6.months.ago.to_date)
  end

  test "import_transactions clamps an expired sync_start_date to the current max lookback" do
    redbark_account = redbark_accounts(:savings_account)
    # Bypass the model's own validation to simulate a date that was valid when
    # set but has since drifted outside the rolling window by the time a
    # delayed first fetch actually runs.
    redbark_account.update_column(:sync_start_date, (RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS + 50).days.ago.to_date)

    assert_fetches_from(redbark_account, RedbarkAccount::MAX_SYNC_START_DATE_LOOKBACK_DAYS.days.ago.to_date)
  end

  test "import_transactions falls back to the default history window when there's no stored date" do
    redbark_account = redbark_accounts(:savings_account)
    redbark_account.update!(sync_start_date: nil)

    assert_fetches_from(redbark_account, RedbarkAccount::DEFAULT_INITIAL_HISTORY_DAYS.days.ago.to_date)
  end

  private

    # Asserts the date window import_transactions actually sends to Redbark,
    # rather than calling calculate_transaction_start_date directly -- that
    # private method's return value composing correctly with the rest of
    # import_transactions is exactly what's under test here.
    def assert_fetches_from(redbark_account, expected_start_date)
      provider = mock("redbark_provider")
      importer = RedbarkItem::Importer.new(@redbark_item, redbark_provider: provider)
      importer.stubs(:transactable_connection?).returns(true)
      importer.stubs(:connections_by_id).returns({})

      provider.expects(:get_transactions).with(
        connection_id: redbark_account.connection_id,
        account_id: redbark_account.redbark_account_id,
        start_date: expected_start_date,
        end_date: Date.current,
        include_pending: Rails.configuration.x.redbark.include_pending
      ).returns([])

      importer.send(:import_transactions, redbark_account)
    end

    def link_card(redbark_account_id)
      item = redbark_accounts(:savings_account).redbark_item
      redbark_account = item.redbark_accounts.create!(redbark_account_id: redbark_account_id, name: "Card", currency: "AUD")
      redbark_account.ensure_account_provider!(
        item.family.accounts.create!(name: "Card", balance: 100, currency: "AUD", accountable: CreditCard.new)
      )
      [ redbark_account, item ]
    end
end