Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
96.0 KB
Raw Blame
require "test_helper"

class AccountsControllerTest < ActionDispatch::IntegrationTest
  include ActionView::RecordIdentifier
  include OnchainTestHelper
  include EntriesTestHelper
  include TradeRepublicSessionTestHelper

  setup do
    sign_in @user = users(:family_admin)
    @account = accounts(:depository)
  end

  test "should get index" do
    get accounts_url
    assert_response :success
    assert_select "p.ml-auto.privacy-sensitive"
  end

  test "account reconciliation indicator renders only on the account page" do
    create_transaction(account: @account, name: "Unreconciled", amount: 10)

    get account_url(@account)

    assert_response :success
    assert_not_includes response.body, I18n.t("accounts.reconciliation_indicator.needs_attention")

    @user.family.update!(manual_reconciliation: true)

    get account_url(@account)

    assert_response :success
    assert_equal 1, response.body.scan(I18n.t("accounts.reconciliation_indicator.needs_attention")).size

    get accounts_url

    assert_response :success
    assert_not_includes response.body, I18n.t("accounts.reconciliation_indicator.needs_attention")

    get root_url

    assert_response :success
    assert_not_includes response.body, I18n.t("accounts.reconciliation_indicator.needs_attention")
  end

  # Opening the account groups makes the list scroll; reserving the scrollbar's
  # space keeps the sidebar from shifting sideways when it appears.
  test "the sidebar keeps room for its scrollbar" do
    get root_url

    assert_select "#sidebar-scroll[class*='[scrollbar-gutter:stable]']"
  end

  test "show points an unmatched transaction with a counterpart to the transfer matcher" do
    outflow = create_transaction(account: @account, name: "Hint outflow", amount: 500, date: Date.current)
    create_transaction(account: accounts(:credit_card), name: "Hint inflow", amount: -500, date: Date.current)

    get account_url(@account)

    assert_response :success
    assert_select "a[href='#{new_transaction_transfer_match_path(outflow)}']", text: I18n.t("transactions.transaction.transfer_hint")
  end

  test "show filters account activity to uncategorized transactions" do
    uncategorized = create_transaction(account: @account, name: "Uncategorized Filter Target", category: nil)
    categorized = create_transaction(account: @account, name: "Categorized Filter Decoy", category: categories(:food_and_drink))

    get account_url(@account, q: { categories: [ Category::UNCATEGORIZED_FILTER_VALUE ] })

    assert_response :success
    assert_match uncategorized.name, response.body
    assert_no_match categorized.name, response.body
  end

  test "index delegates whole-row account clicks to the account link" do
    get accounts_url

    assert_response :success
    doc = Nokogiri::HTML::Document.parse(response.body)
    row = doc.at_css("turbo-frame##{dom_id(@account)} [data-controller='clickable-row']")
    account_link = row.at_css("a[data-clickable-row-target='link']")

    assert_equal "click->clickable-row#open", row["data-action"]
    assert_equal account_path(@account), account_link["href"]
  end

  test "index shows the excluded-from-reports indicator with its explanation" do
    @account.update!(exclude_from_reports: true)

    get accounts_url

    assert_response :success
    doc = Nokogiri::HTML::Document.parse(response.body)
    frame = doc.at_css("turbo-frame##{dom_id(@account)}")
    text = I18n.t("accounts.account.excluded_from_reports_indicator")
    panel = frame.css("[role='tooltip']").find { |node| node.text.strip == text }
    assert panel, "expected a tooltip panel with the indicator text"
    assert_nil panel.at_css("svg"), "the tooltip panel should show text, not the icon"

    trigger = frame.at_css("[aria-describedby='#{panel["id"]}']")
    assert_equal "button", trigger.name
    assert_equal eye_off_icon_paths, trigger.css("svg path").map { |path| path["d"] }, "the trigger should be the eye-off icon"
  end

  test "index omits the excluded-from-reports indicator for included accounts" do
    @account.update!(exclude_from_reports: false)

    get accounts_url

    assert_response :success
    frame = Nokogiri::HTML::Document.parse(response.body).at_css("turbo-frame##{dom_id(@account)}")
    text = I18n.t("accounts.account.excluded_from_reports_indicator")
    assert_empty frame.css("[role='tooltip']").select { |node| node.text.strip == text }
    assert_not_includes frame.text, text
  end

  test "index localizes the Plaid add accounts action" do
    ensure_tailwind_build
    @user.update!(locale: "de")

    get accounts_url

    assert_response :success
    assert_select "a[href=?]",
                  edit_plaid_item_path(plaid_items(:one), add_accounts: true),
                  text: "Konten hinzufügen",
                  count: 1
  end

  test "index renders kraken items" do
    kraken_item = kraken_items(:one)
    get accounts_url
    assert_response :success
    assert_select "##{dom_id(kraken_item)}"
  end

  test "index titles each ibkr connection with its own name" do
    first = ibkr_items(:configured_item)
    first.update!(name: "IBKR Ireland")
    second = @user.family.ibkr_items.create!(name: "IBKR US", query_id: "Q2", token: "T2")

    get accounts_url

    assert_response :success
    assert_select "##{dom_id(first)}", text: /IBKR Ireland/
    assert_select "##{dom_id(second)}", text: /IBKR US/
  end

  test "index renders on-chain wallet items" do
    register_fake_chain!
    item = create_onchain_wallet_item(family: @user.family)
    onchain_account = create_onchain_wallet_account(item: item)
    onchain_account.ensure_account_provider!(accounts(:investment))

    get accounts_url

    assert_response :success
    # Without this the wallet is invisible here: its accounts carry a provider
    # link, so Account.manual excludes them, and no provider section claimed them.
    assert_select "##{dom_id(item, :accounts_index)}"
    # The card carries the same actions menu every other provider card does.
    assert_select "form[action=?]", sync_onchain_wallet_item_path(item)
    assert_select "form[action=?]", onchain_wallet_item_path(item)
  ensure
    unregister_fake_chain!
  end

  test "index does not leak wallet accounts a member was never given" do
    register_fake_chain!
    admin = users(:family_admin)
    member = users(:family_member)
    item = create_onchain_wallet_item(family: admin.family)

    shared = accounts(:investment)
    unshared = accounts(:credit_card)
    [ shared, unshared ].each_with_index do |account, index|
      account.update!(owner: admin)
      account.account_shares.destroy_all
      row = create_onchain_wallet_account(
        item: item,
        address: "#{OnchainTestHelper::FAKE_ADDRESS}#{index}"
      )
      row.ensure_account_provider!(account)
    end
    shared.account_shares.create!(user: member, permission: "read_only")

    sign_in member
    get accounts_url

    assert_response :success
    assert_select "##{dom_id(item, :accounts_index)}"
    # The item is surfaced as soon as ONE of its accounts is accessible, so
    # rendering them all would hand a partially-authorised member the names and
    # balances of accounts nobody shared with them.
    assert_includes response.body, shared.name
    assert_not_includes response.body, unshared.name
  ensure
    unregister_fake_chain!
  end

  # #3630. A provider card is admitted for a member as soon as ONE of its
  # accounts is shared with them, so the card must list only the accounts this
  # viewer may see. The unshared account is renamed to something no other part
  # of the page can print, so its absence proves the card filtered it.
  test "a partially shared member sees only their account on a Plaid card" do
    shared, unshared = link_two_accounts_to(plaid_items(:one)) do |item, index|
      item.plaid_accounts.create!(
        name: "Second Plaid Account", plaid_id: "acc_235_#{index}", plaid_type: "investment",
        currency: "USD", current_balance: 10
      )
    end

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_select "##{dom_id(plaid_items(:one))}"
    assert_select "turbo-frame##{dom_id(shared)}", count: 1
    assert_select "turbo-frame##{dom_id(unshared)}", count: 0
    assert_not_includes response.body, unshared.name
  end

  test "an admin still sees every account on a Plaid card" do
    shared, unshared = link_two_accounts_to(plaid_items(:one)) do |item, index|
      item.plaid_accounts.create!(
        name: "Second Plaid Account", plaid_id: "acc_235_#{index}", plaid_type: "investment",
        currency: "USD", current_balance: 10
      )
    end

    get accounts_url

    assert_response :success
    assert_select "turbo-frame##{dom_id(shared)}", count: 1
    assert_select "turbo-frame##{dom_id(unshared)}", count: 1
  end

  test "a partially shared member sees only their account on a SimpleFIN card" do
    item = SimplefinItem.create!(family: families(:dylan_family), name: "Conn 235", access_url: "https://example.com/access")
    shared, unshared = link_two_accounts_to(item) do |sf_item, index|
      sf_item.simplefin_accounts.create!(
        name: "SF #{index}", account_id: "sf_235_#{index}", currency: "USD",
        current_balance: 1, account_type: "depository"
      )
    end

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_select "##{dom_id(item)}"
    assert_select "turbo-frame##{dom_id(shared)}", count: 1
    assert_select "turbo-frame##{dom_id(unshared)}", count: 0
    assert_not_includes response.body, unshared.name
  end

  # The card's other name-bearing lists. The sync summary's detail rows come
  # from the connection's last sync and name the accounts and transactions
  # involved, so they follow the same rule as the account list: shown only to
  # a viewer who can see every account on the connection. Counts stay.
  test "a partially shared member does not see account names in a card's sync summary" do
    item = plaid_items(:one)
    _shared, unshared = link_two_accounts_to(item) do |p_item, index|
      p_item.plaid_accounts.create!(
        name: "Second Plaid Account", plaid_id: "acc_235_#{index}", plaid_type: "investment",
        currency: "USD", current_balance: 10
      )
    end
    item.syncs.create!(status: "completed", sync_stats: {
      "tx_seen" => 1, "tx_skipped" => 1,
      "skip_details" => [ { "name" => "Secret Txn 235", "reason" => "excluded", "account_name" => unshared.name } ],
      "total_errors" => 1,
      "errors" => [ { "name" => unshared.name, "message" => "Import failed 235" } ]
    })

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_not_includes response.body, unshared.name
    assert_not_includes response.body, "Secret Txn 235"
  end

  test "an admin still sees the account names in a card's sync summary" do
    item = plaid_items(:one)
    link_two_accounts_to(item) do |p_item, index|
      p_item.plaid_accounts.create!(
        name: "Second Plaid Account", plaid_id: "acc_235_#{index}", plaid_type: "investment",
        currency: "USD", current_balance: 10
      )
    end
    item.syncs.create!(status: "completed", sync_stats: {
      "tx_seen" => 1, "tx_skipped" => 1,
      "skip_details" => [ { "name" => "Secret Txn 235", "reason" => "excluded", "account_name" => "x" } ]
    })

    get accounts_url

    assert_response :success
    assert_includes response.body, "Secret Txn 235"
  end

  test "a partially shared member does not see unshared names in SimpleFIN's stale-pending and replacement banners" do
    item = SimplefinItem.create!(family: families(:dylan_family), name: "Conn 235", access_url: "https://example.com/access")
    _shared, unshared = link_two_accounts_to(item) do |sf_item, index|
      sf_item.simplefin_accounts.create!(
        name: "SF #{index}", account_id: "sf_235_#{index}", currency: "USD",
        current_balance: 1, account_type: "depository"
      )
    end
    SimplefinItem.any_instance.stubs(:stale_pending_status)
                 .returns({ count: 2, message: "2 pending", accounts: [ unshared.name ] })
    item.syncs.create!(status: "completed", sync_stats: {
      "replacement_suggestions" => [ {
        "dormant_sfa_id" => item.simplefin_accounts.find_by!(account_id: "sf_235_1").id,
        "active_sfa_id" => item.simplefin_accounts.find_by!(account_id: "sf_235_0").id,
        "sure_account_id" => unshared.id
      } ]
    })

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_select "##{dom_id(item)}"
    assert_not_includes response.body, unshared.name
  end

  # The card header names the connected institution when there is only one.
  # That institution is the unshared account's as much as the shared one's,
  # so it follows the same rule as the other names on the card.
  test "a partially shared member does not see the connection's institution name" do
    item = SimplefinItem.create!(family: families(:dylan_family), name: "Conn 235", access_url: "https://example.com/access")
    link_two_accounts_to(item) do |sf_item, index|
      sf_item.simplefin_accounts.create!(
        name: "SF #{index}", account_id: "sf_235_#{index}", currency: "USD",
        current_balance: 1, account_type: "depository"
      )
    end
    SimplefinItem.any_instance.stubs(:connected_institutions).returns([ { "name" => "Hidden Bank 235" } ])

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_select "##{dom_id(item)}"
    assert_not_includes response.body, "Hidden Bank 235"
  end

  test "an admin still sees the connection's institution name" do
    item = SimplefinItem.create!(family: families(:dylan_family), name: "Conn 235", access_url: "https://example.com/access")
    link_two_accounts_to(item) do |sf_item, index|
      sf_item.simplefin_accounts.create!(
        name: "SF #{index}", account_id: "sf_235_#{index}", currency: "USD",
        current_balance: 1, account_type: "depository"
      )
    end
    SimplefinItem.any_instance.stubs(:connected_institutions).returns([ { "name" => "Hidden Bank 235" } ])

    get accounts_url

    assert_response :success
    assert_includes response.body, "Hidden Bank 235"
  end

  # The SnapTrade card's brokerage line is built from every
  # account on the connection. With one brokerage it prints that brokerage's
  # name, so a member shared only the nameless account would read the other's.
  test "a partially shared member does not see a SnapTrade connection's brokerage" do
    item = snaptrade_items(:configured_item)
    # The fixture accounts name two brokerages, which makes the line a count.
    # Cleared so the only brokerage left is the unshared account's.
    item.snaptrade_accounts.update_all(brokerage_name: nil)
    link_two_accounts_to(item) do |st_item, index|
      st_item.snaptrade_accounts.create!(
        name: "ST #{index}", snaptrade_account_id: "st_235_#{index}", currency: "USD",
        current_balance: 1, brokerage_name: (index.zero? ? nil : "Hidden Broker 235")
      )
    end

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_select "##{dom_id(item)}"
    assert_not_includes response.body, "Hidden Broker 235"
  end

  test "an admin still sees a SnapTrade connection's brokerage" do
    item = snaptrade_items(:configured_item)
    # The fixture accounts name two brokerages, which makes the line a count.
    # Cleared so the only brokerage left is the unshared account's.
    item.snaptrade_accounts.update_all(brokerage_name: nil)
    link_two_accounts_to(item) do |st_item, index|
      st_item.snaptrade_accounts.create!(
        name: "ST #{index}", snaptrade_account_id: "st_235_#{index}", currency: "USD",
        current_balance: 1, brokerage_name: (index.zero? ? nil : "Hidden Broker 235")
      )
    end

    get accounts_url

    assert_response :success
    assert_includes response.body, "Hidden Broker 235"
  end

  test "a partially shared member sees only their account on a Kraken card" do
    item = kraken_items(:one)
    shared, unshared = link_two_accounts_to(item) do |k_item, index|
      k_item.kraken_accounts.create!(
        name: "Kraken #{index}", account_id: "kraken_235_#{index}", account_type: "combined",
        currency: "USD", current_balance: 1, extra: {}
      )
    end

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_select "##{dom_id(item)}"
    assert_select "turbo-frame##{dom_id(shared)}", count: 1
    assert_select "turbo-frame##{dom_id(unshared)}", count: 0
  end

  test "a partially shared member does not see stale-rate warnings for an unshared Kraken account" do
    item = kraken_items(:one)
    shared, unshared = link_two_accounts_to(item) do |k_item, index|
      k_item.kraken_accounts.create!(
        name: "Kraken #{index}", account_id: "kraken_stale_#{index}", account_type: "combined",
        currency: "USD", current_balance: 1,
        extra: index.zero? ? {} : { "kraken" => { "stale_rate" => "true", "rate_target_date" => "2001-02-03" } }
      )
    end

    sign_in users(:family_member)
    get accounts_url
    assert_response :success
    assert_select "##{dom_id(item)}"
    assert_not_includes response.body, "2001-02-03"

    sign_in users(:family_admin)
    get accounts_url
    assert_includes response.body, "2001-02-03"
  end

  test "a partially shared member does not see a Trade Republic connection's data-quality totals" do
    item = trade_republic_items(:configured_item)
    # The fixture item already has one portfolio and one cash account, and
    # the database allows one of each kind per connection.
    link_two_accounts_to(item) do |_item, index|
      trade_republic_accounts(index.zero? ? :main_account : :cash_account)
    end
    title = I18n.t("trade_republic_items.trade_republic_item.data_quality.title")

    sign_in users(:family_member)
    get accounts_url
    assert_response :success
    assert_select "##{dom_id(item)}"
    assert_not_includes response.body, title

    sign_in users(:family_admin)
    get accounts_url
    assert_includes response.body, title
  end

  # The default trail ends on "Accounts", which is never a link, so an account's
  # page had no way back to the accounts list.
  test "show links the Accounts crumb back to the accounts list" do
    get account_url(@account)

    assert_response :success
    assert_select "[data-breadcrumbs] a[href=?]", accounts_path, text: I18n.t("breadcrumbs.accounts")
    assert_select "[data-breadcrumbs] > span:last-child", text: @account.name
  end

  test "the accounts list itself stays the unlinked current crumb" do
    get accounts_url

    assert_response :success
    assert_select "[data-breadcrumbs] a[href=?]", accounts_path, count: 0
    assert_select "[data-breadcrumbs] > span:last-child", text: I18n.t("breadcrumbs.accounts")
  end

  test "index offers a QR login on a Trade Republic connection that needs one" do
    item = trade_republic_items(:configured_item)
    item.update!(session_blob: trade_republic_session_blob(expires_at: 1.minute.ago))

    get accounts_url

    assert_response :success
    assert_select "##{dom_id(item)} [data-trade-republic-qr-initiate-url-value='#{initiate_qr_login_trade_republic_item_path(item)}']"
    assert_select "##{dom_id(item)} [data-trade-republic-qr-return-url-value='#{accounts_path}']"
    # Until then a sync can only fail.
    assert_select "##{dom_id(item)} form[action='#{sync_trade_republic_item_path(item)}'] button[disabled]"
  end

  test "index shows when a Trade Republic login expires" do
    item = trade_republic_items(:configured_item)
    item.update!(session_blob: trade_republic_session_blob(expires_at: 5.hours.from_now))

    get accounts_url

    assert_response :success
    assert_includes response.body, I18n.t("trade_republic_items.trade_republic_item.session_expires_in",
                                          time: "about 5 hours", at: I18n.l(item.reload.session_expires_at, format: :short))
    assert_select "##{dom_id(item)} [data-controller='trade-republic-qr']", count: 0
  end

  test "index renders trading212 items" do
    trading212_item = trading212_items(:configured_item)
    get accounts_url
    assert_response :success
    assert_select "##{dom_id(trading212_item)}"
  end

  test "index renders only accessible accounts for a visible trading212 item" do
    accessible_account = accounts(:depository)
    inaccessible_account = accounts(:investment)
    trading212_item = trading212_items(:configured_item)
    trading212_accounts(:main_account).ensure_account_provider!(accessible_account)
    trading212_item.trading212_accounts.create!(
      name: "Private Trading 212 Account",
      trading212_account_id: "t212_private_123",
      currency: "USD",
      current_balance: 1000,
      cash_balance: 100,
      raw_positions_payload: [],
      raw_orders_payload: [],
      raw_dividends_payload: [],
      raw_transactions_payload: []
    ).ensure_account_provider!(inaccessible_account)
    sign_in users(:family_member)

    get accounts_url

    assert_response :success
    assert_select "##{dom_id(trading212_item)}"
    assert_select "turbo-frame##{dom_id(accessible_account)}", count: 1
    assert_select "turbo-frame##{dom_id(inaccessible_account)}", count: 0
  end

  test "index renders only trading212 items with accessible accounts for members" do
    shared_account = accounts(:credit_card)
    trading212_accounts(:main_account).ensure_account_provider!(shared_account)
    sign_in users(:family_member)

    get accounts_url

    assert_response :success
    assert_select "##{dom_id(trading212_items(:configured_item))}"
    assert_select "##{dom_id(trading212_items(:pending_setup_item))}", count: 0
  end

  test "should get show" do
    get account_url(@account)
    assert_response :success
  end

  test "show lists positions that went below zero in the account status" do
    account = accounts(:investment)
    # An import that records a sale without its purchase, as a provider or CSV can.
    account.entries.create!(
      name: "Sell 3 shares of MSFT", date: 3.days.ago.to_date, amount: -1200, currency: "USD",
      entryable: Trade.new(security: securities(:msft), qty: -3, price: 400, currency: "USD", investment_activity_label: "Sell")
    )
    Holding::Materializer.new(account, strategy: :forward).materialize_holdings

    get account_url(account)

    assert_response :success
    assert_select "[data-testid='account-health-status']", text: /Microsoft \(MSFT\): below zero from/
  end

  test "show has no account status for a healthy account" do
    get account_url(@account)

    assert_response :success
    assert_select "[data-testid='account-health-status']", count: 0
  end

  test "a member who cannot open the account does not see its status" do
    account = accounts(:investment)
    account.syncs.create!(status: :failed, failed_at: 1.hour.ago)
    sign_in users(:family_member)

    get account_url(account)

    assert_response :not_found
    assert_not_includes response.body, I18n.t("accounts.health_status.sync_failed.message")
  end

  test "a member sees the status of an account shared with them" do
    @account.syncs.create!(status: :failed, failed_at: 1.hour.ago)
    sign_in users(:family_member)

    get account_url(@account)

    assert_response :success
    assert_select "[data-testid='account-health-status']", text: /#{I18n.t("accounts.health_status.sync_failed.message")}/
  end

  test "show renders the scheduled balance tooltip when a scheduled transaction exists" do
    create_transaction(account: @account, amount: 200, date: 3.days.from_now.to_date)

    get account_url(@account)

    assert_response :success
    assert_select "[data-controller='DS--tooltip']"
  end

  test "show adds the scheduled projection to the investment value tooltip" do
    investment_account = accounts(:investment)
    create_transaction(account: investment_account, amount: 200, date: 3.days.from_now.to_date)

    get account_url(investment_account)

    assert_response :success
    assert_select "[role='tooltip']", text: /#{I18n.t("investments.value_tooltip.projected")}/
  end

  test "show omits the scheduled projection from the investment value tooltip without scheduled entries" do
    get account_url(accounts(:investment))

    assert_response :success
    assert_select "[role='tooltip']", text: /#{I18n.t("investments.value_tooltip.projected")}/, count: 0
  end

  test "show renders the balance chart as drag-selectable for a custom date range" do
    get account_url(@account)

    assert_response :success
    assert_select "#lineChart[data-time-series-chart-selectable-value='true']"
  end

  test "show honors a custom start_date/end_date range" do
    start_date = 15.days.ago.to_date
    end_date = Date.current

    get account_url(@account), params: { start_date: start_date.to_s, end_date: end_date.to_s }

    assert_response :success
    # If the params were ignored, the user's default preset would render as the
    # checked option instead of the custom row.
    assert_select "a[role='menuitemradio'][aria-checked='true'][href*='period=']", count: 0
    assert_select "a[role='menuitemradio'][aria-checked='true'][href*='start_date=']", count: 1
  end

  test "show filter menu offers the same filters as transactions except the account tab" do
    get account_url(@account)

    assert_response :success
    assert_select "#transaction-filters-menu button[data-id=?]", "account_filter", count: 0
    assert_select "#transaction-filters-menu button[data-id=?]", "category_filter", count: 1
    assert_select "#transaction-filters-menu button[data-id=?]", "tag_filter", count: 1
    assert_select "#transaction-filters-menu button[data-id=?]", "merchant_filter", count: 1
    assert_select "#transaction-filters-menu button[data-id=?]", "type_filter", count: 1
  end

  test "show filters activity by category and excludes non-Transaction entries" do
    categorized = create_transaction(name: "Categorized", amount: 50, account: @account, category: categories(:food_and_drink))
    uncategorized = create_transaction(name: "Uncategorized", amount: 60, account: @account)
    valuation = @account.entries.create!(
      name: "Balance update", date: 1.day.ago.to_date, amount: 1000, currency: "USD", entryable: Valuation.new
    )

    get account_url(@account), params: { q: { categories: [ "Food & Drink" ] } }

    assert_response :success
    assert_select "##{dom_id(categorized)}"
    assert_select "##{dom_id(uncategorized)}", count: 0
    assert_select "##{dom_id(valuation)}", count: 0
  end

  test "show filters activity by reconciliation status on a manual account" do
    @user.family.update!(manual_reconciliation: true)
    cleared = create_transaction(name: "Cleared", amount: 50, account: @account)
    cleared.update!(reconciled_status: "cleared")
    unreconciled = create_transaction(name: "Unreconciled", amount: 60, account: @account)

    get account_url(@account), params: { q: { reconcile_status: [ "cleared" ] } }

    assert_response :success
    assert_select "##{dom_id(cleared)}"
    assert_select "##{dom_id(unreconciled)}", count: 0
    assert_select "#transaction-filters-menu button[data-id=?]", "reconcile_status_filter"
  end

  test "show hides the reconciliation filter on a synced account and drops the param" do
    @user.family.update!(manual_reconciliation: true)
    synced_account = accounts(:connected)
    entry = create_transaction(name: "Synced entry", amount: 50, account: synced_account)

    get account_url(synced_account), params: { q: { reconcile_status: [ "unreconciled" ] } }

    assert_response :success
    assert_select "#transaction-filters-menu button[data-id=?]", "reconcile_status_filter", count: 0
    assert_select "##{dom_id(entry)}"
  end

  test "reconcile_all marks every transaction on a manual account and keeps statement data" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    first = create_transaction(account: account, name: "First", amount: 10)
    second = create_transaction(account: account, name: "Second", amount: 20)
    valuation = create_valuation(account: account, date: 2.days.ago.to_date)
    other_account_entry = create_transaction(account: accounts(:credit_card), name: "Other account")
    reconciled_at = 2.days.ago.change(usec: 0)
    first.update_columns(reconciled_at: reconciled_at)

    patch reconcile_all_account_url(account), params: { reconciled_status: "reconciled" }

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.reconcile_all.success", count: 2, status: I18n.t("transactions.reconcile.statuses.reconciled")), flash[:notice]
    assert_equal %w[reconciled reconciled], [ first, second ].map { |entry| entry.reload.reconciled_status }
    assert_equal reconciled_at, first.reload.reconciled_at
    assert_equal "unreconciled", valuation.reload.reconciled_status
    assert_equal "unreconciled", other_account_entry.reload.reconciled_status
  end

  test "reconcile_all rejects a synced account" do
    @user.family.update!(manual_reconciliation: true)
    account = accounts(:connected)
    entry = create_transaction(account: account, name: "Synced")

    patch reconcile_all_account_url(account), params: { reconciled_status: "reconciled" }

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.reconcile_all.not_manual_account"), flash[:alert]
    assert_equal "unreconciled", entry.reload.reconciled_status
  end

  test "reconcile_all rejects an unknown status" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    entry = create_transaction(account: account, name: "Untouched")

    patch reconcile_all_account_url(account), params: { reconciled_status: "bogus" }

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.reconcile_all.invalid_status"), flash[:alert]
    assert_equal "unreconciled", entry.reload.reconciled_status
  end

  test "reconcile_all returns not found when manual reconciliation is disabled" do
    account = create_manual_account
    entry = create_transaction(account: account, name: "Untouched")

    patch reconcile_all_account_url(account), params: { reconciled_status: "reconciled" }

    assert_response :not_found
    assert_equal "unreconciled", entry.reload.reconciled_status
  end

  test "reconcile_all requires write permission" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    entry = create_transaction(account: account, name: "Untouched")
    member = users(:family_member)
    account.account_shares.create!(user: member, permission: "read_only")

    sign_in member
    patch reconcile_all_account_url(account), params: { reconciled_status: "reconciled" }

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
    assert_equal "unreconciled", entry.reload.reconciled_status
  end

  test "show offers bulk reconciliation only on an eligible manual account" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    create_transaction(account: account, name: "Transaction")

    get account_url(account)

    assert_response :success
    assert_select "[data-testid='account-menu']" do
      assert_select "button", text: /#{I18n.t("accounts.show.menu.reconcile_all.unreconciled")}/
      assert_select "button", text: /#{I18n.t("accounts.show.menu.reconcile_all.cleared")}/
      assert_select "button", text: /#{I18n.t("accounts.show.menu.reconcile_all.reconciled")}/
    end
    assert_select "form[action=?]", reconcile_all_account_path(account, reconciled_status: "reconciled")
  end

  test "show hides bulk reconciliation without the family setting" do
    account = create_manual_account
    create_transaction(account: account, name: "Transaction")

    get account_url(account)

    assert_response :success
    assert_select "form[action=?]", reconcile_all_account_path(account, reconciled_status: "reconciled"), count: 0
  end

  test "show hides bulk reconciliation on a synced account" do
    @user.family.update!(manual_reconciliation: true)
    account = accounts(:connected)
    create_transaction(account: account, name: "Synced")

    get account_url(account)

    assert_response :success
    assert_select "form[action=?]", reconcile_all_account_path(account, reconciled_status: "reconciled"), count: 0
  end

  test "show hides bulk reconciliation on an account without transactions" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account

    get account_url(account)

    assert_response :success
    assert_select "form[action=?]", reconcile_all_account_path(account, reconciled_status: "reconciled"), count: 0
  end

  test "show hides bulk reconciliation from a read-only share" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    create_transaction(account: account, name: "Transaction")
    member = users(:family_member)
    account.account_shares.create!(user: member, permission: "read_only")

    sign_in member
    get account_url(account)

    assert_response :success
    assert_select "form[action=?]", reconcile_all_account_path(account, reconciled_status: "reconciled"), count: 0
  end

  test "reconcile_all allows a member with full_control" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    entry = create_transaction(account: account, name: "Shared")
    member = users(:family_member)
    account.account_shares.create!(user: member, permission: "full_control")

    sign_in member
    patch reconcile_all_account_url(account), params: { reconciled_status: "cleared" }

    assert_redirected_to account_url(account)
    assert_equal "cleared", entry.reload.reconciled_status
  end

  test "reconcile_all treats a missing status as invalid" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    entry = create_transaction(account: account, name: "Untouched")

    patch reconcile_all_account_url(account)

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.reconcile_all.invalid_status"), flash[:alert]
    assert_equal "unreconciled", entry.reload.reconciled_status
  end

  test "reconcile_all reports zero updates for an account without transactions" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account

    patch reconcile_all_account_url(account), params: { reconciled_status: "cleared" }

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.reconcile_all.success", count: 0, status: I18n.t("transactions.reconcile.statuses.cleared")), flash[:notice]
  end

  test "reconcile_all does not reach an account in another family" do
    @user.family.update!(manual_reconciliation: true)
    other_account = Account.create!(
      family: families(:inactive_trial),
      name: "Someone else's account",
      balance: 0,
      currency: "USD",
      accountable: Depository.new
    )

    patch reconcile_all_account_url(other_account), params: { reconciled_status: "reconciled" }

    assert_response :not_found
  end

  test "show hides bulk reconciliation on an account with only valuations" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    create_valuation(account: account, date: 2.days.ago.to_date)

    get account_url(account)

    assert_response :success
    assert_select "form[action=?]", reconcile_all_account_path(account, reconciled_status: "reconciled"), count: 0
  end

  test "the bulk reconciliation items carry a confirmation" do
    @user.family.update!(manual_reconciliation: true)
    account = create_manual_account
    create_transaction(account: account, name: "Transaction")

    get account_url(account)

    assert_response :success
    Entry.reconciled_statuses.each_key do |status|
      assert_select "form[action=?] button[data-turbo-confirm]",
                    reconcile_all_account_path(account, reconciled_status: status)
    end
  end

  test "show hides balance updates on a linked account by default" do
    account = accounts(:connected)
    transaction = create_transaction(account: account, name: "Linked Transaction")
    balance_update = create_valuation(account: account, date: 2.days.ago.to_date)

    get account_url(account)

    assert_response :success
    assert_select "##{dom_id(transaction)}"
    assert_select "##{dom_id(balance_update)}", count: 0
    assert_select "#transaction-filters-menu button[data-id=?]", "balance_updates_filter", count: 1
    assert_select "input[type=checkbox][name=?]:not([checked])", "q[balance_updates]"
  end

  test "show lists balance updates on a linked account when the preference is on" do
    account = accounts(:connected)
    balance_update = create_valuation(account: account, date: 2.days.ago.to_date, name: "Manual balance update")
    @user.update_show_balance_updates(true)

    get account_url(account)

    assert_response :success
    assert_select "##{dom_id(balance_update)}", text: /Synced balance/
    # Nothing left to switch in the filter: it shows as on, and points to Preferences.
    assert_select "input[type=checkbox][name=?][checked][disabled]", "q[balance_updates]"
    assert_select "#account-activity-filters li", count: 0
  end

  test "the activity filter shows balance updates for one view without saving the preference" do
    account = accounts(:connected)
    balance_update = create_valuation(account: account, date: 2.days.ago.to_date)

    get account_url(account), params: { q: { balance_updates: "show", search: "Valuation" } }

    assert_response :success
    assert_select "##{dom_id(balance_update)}"
    assert_select "#account-activity-filters li", count: 2
    assert_select "#account-activity-filters li", text: /Synced balances/
    assert_not @user.reload.show_balance_updates?
  end

  test "clearing the balance updates badge hides them again and keeps the other filters" do
    account = accounts(:connected)

    delete clear_filter_account_url(account), params: {
      q: { balance_updates: "show", search: "Valuation" },
      param_key: "balance_updates",
      param_value: "show"
    }

    assert_redirected_to account_url(account, q: { search: "Valuation" }, tab: "activity", page: nil, per_page: nil)
  end

  test "show lists balance updates on a manual account without offering the filter" do
    balance_update = create_valuation(account: @account, date: 2.days.ago.to_date)

    get account_url(@account)

    assert_response :success
    assert_select "##{dom_id(balance_update)}"
    assert_select "#transaction-filters-menu button[data-id=?]", "balance_updates_filter", count: 0
  end

  test "show omits the balance updates filter on a linked account without any" do
    account = accounts(:connected)
    account.entries.balance_updates.destroy_all

    get account_url(account)

    assert_response :success
    assert_select "#transaction-filters-menu button[data-id=?]", "balance_updates_filter", count: 0
  end

  test "show renders a badge for each active filter" do
    get account_url(@account), params: { q: { categories: [ "Food & Drink" ], search: "grocery" } }

    assert_response :success
    assert_select "#account-activity-filters li", count: 2
  end

  test "show renders badge delete links that preserve the other active filters" do
    get account_url(@account), params: { q: { categories: [ "Food & Drink" ], search: "grocery" } }

    assert_response :success
    doc = Nokogiri::HTML::Document.parse(response.body)
    badge = doc.css("#account-activity-filters li").find { |li| li.text.include?("Food & Drink") }
    form = badge&.at_css("form")

    assert_not_nil form, "expected the category badge to render a delete form"
    action_uri = URI.parse(form["action"])
    action_params = Rack::Utils.parse_nested_query(action_uri.query)

    # Regression: the badge's delete link must carry the *other* active
    # filters along (like clear_filter_transactions_path does via
    # request.query_parameters), or clearing one filter wipes them all.
    assert_equal "grocery", action_params.dig("q", "search"),
      "clearing the category badge must not drop the search filter from the delete link"
  end

  test "clear_filter removes only the targeted filter value and preserves the rest" do
    delete clear_filter_account_url(@account), params: {
      q: { categories: [ "Food & Drink" ], search: "grocery" },
      param_key: "categories",
      param_value: "Food & Drink"
    }

    assert_redirected_to account_url(@account, q: { search: "grocery" }, tab: "activity", page: nil, per_page: nil)
  end

  test "clear_filter keeps the chart's range and view" do
    delete clear_filter_account_url(@account), params: {
      q: { start_date: "2026-01-05", end_date: "2026-02-10" },
      start_date: "2026-01-05", end_date: "2026-02-10", chart_view: "balance",
      param_key: "start_date",
      param_value: "2026-01-05"
    }

    assert_redirected_to account_url(@account, q: { end_date: "2026-02-10" }, tab: "activity",
                                               start_date: "2026-01-05", end_date: "2026-02-10", chart_view: "balance")
  end

  test "show's period links keep the activity filters but not the dates of the range they replace" do
    get account_url(@account), params: {
      start_date: "2026-01-05", end_date: "2026-02-10",
      q: { start_date: "2026-01-05", end_date: "2026-02-10", search: "grocery" }
    }

    assert_response :success
    preset = css_select("a[role='menuitemradio']").find { |link| link["href"].include?("period=last_90_days") }
    query = Rack::Utils.parse_nested_query(URI.parse(preset["href"]).query)
    assert_equal({ "search" => "grocery" }, query["q"])
  end

  test "show's chart-view select keeps a dragged range and the activity filters" do
    get account_url(accounts(:investment)), params: {
      start_date: "2026-01-05", end_date: "2026-02-10",
      q: { start_date: "2026-01-05", end_date: "2026-02-10", search: "grocery" }
    }

    assert_response :success
    form = css_select("form").find { |f| f.at_css("select[name='chart_view']") }
    hidden = form.css("input[type='hidden']").to_h { |input| [ input["name"], input["value"] ] }
    assert_equal "2026-01-05", hidden["start_date"]
    assert_equal "2026-02-10", hidden["end_date"]
    assert_equal "2026-01-05", hidden["q[start_date]"]
    assert_equal "2026-02-10", hidden["q[end_date]"]
    assert_equal "grocery", hidden["q[search]"]
  end

  test "show's chart-view select carries no range for a preset period" do
    get account_url(accounts(:investment)), params: { period: "last_90_days" }

    assert_response :success
    form = css_select("form").find { |f| f.at_css("select[name='chart_view']") }
    names = form.css("input[type='hidden']").map { |input| input["name"] }
    assert_not_includes names, "start_date"
    assert_not_includes names, "end_date"
  end

  test "show's activity search keeps the chart's range and view for its badges' clear links" do
    get account_url(accounts(:investment)), params: {
      start_date: "2026-01-05", end_date: "2026-02-10", chart_view: "holdings_balance", tab: "activity"
    }

    assert_response :success
    form = css_select("form").find { |f| f.at_css("input[name='q[search]']") }
    hidden = form.css("input[type='hidden']").to_h { |input| [ input["name"], input["value"] ] }
    assert_equal "2026-01-05", hidden["start_date"]
    assert_equal "2026-02-10", hidden["end_date"]
    assert_equal "holdings_balance", hidden["chart_view"]
  end

  test "clear_filter drops the amount_operator once amount is cleared" do
    delete clear_filter_account_url(@account), params: {
      q: { amount: "50", amount_operator: "equal" },
      param_key: "amount",
      param_value: "50"
    }

    assert_redirected_to account_url(@account, q: nil, tab: "activity", page: nil, per_page: nil)
  end

  test "show renders without missing translations" do
    get account_url(@account)

    assert_response :success
    assert_empty response.body.scan(/translation missing: [\w.]+/).uniq
  end

  test "sync all requests fresh Plaid transactions before syncing the family" do
    sequence = sequence("manual sync all")
    Family.any_instance
      .expects(:request_plaid_transactions_refreshes_later)
      .with(source: "AccountsController#sync_all")
      .in_sequence(sequence)
    Family.any_instance.expects(:sync_later).once.in_sequence(sequence)

    post sync_all_accounts_url

    assert_redirected_to accounts_url
  end

  test "sync all continues when Plaid refresh orchestration cannot be enqueued" do
    PlaidTransactionsRefreshAllJob.stubs(:perform_later).raises(RedisClient::Error, "Redis unavailable")
    Family.any_instance.expects(:sync_later).once

    post sync_all_accounts_url

    assert_redirected_to accounts_url
  end

  test "show avoids N+1 transfer queries across paginated entries" do
    queries = capture_sql_queries { get account_url(@account) }
    assert_response :success

    # Per-row transfer lookups (N+1 pattern) hit transfers with a single id
    # Preloading batches them into IN(...) — assert no single-id lookups remain
    per_row_transfer = queries.count { |q|
      q.match?(/FROM "transfers".*WHERE.*"(inflow|outflow)_transaction_id"/) &&
        !q.include?(" IN (")
    }
    assert_equal 0, per_row_transfer, "N+1 per-row transfer queries detected (#{per_row_transfer})"
  end

  test "show delegates whole-row trade clicks to the drawer link" do
    investment_account = accounts(:investment)
    entry = entries(:trade)

    get account_url(investment_account)

    assert_response :success
    doc = Nokogiri::HTML::Document.parse(response.body)
    row = doc.at_css("turbo-frame##{dom_id(entry.entryable)} [data-controller='clickable-row']")
    drawer_link = row.at_css("a[data-clickable-row-target='link']")

    assert_equal "click->clickable-row#open", row["data-action"]
    assert_equal entry_path(entry), drawer_link["href"]
  end

  test "show avoids N+1 split-parent queries across paginated entries" do
    queries = capture_sql_queries { get account_url(@account) }
    assert_response :success

    # Per-row child-entry existence checks (N+1) hit entries with a single parent_entry_id
    # @split_parent_entry_ids preloads this in one batch IN query
    per_row_split = queries.count { |q|
      q.match?(/FROM "entries".*WHERE.*"parent_entry_id"/) && !q.include?(" IN (")
    }
    assert_equal 0, per_row_split, "N+1 per-row split-parent queries detected (#{per_row_split})"
  end

  test "show groups split transactions into a single split-group row when grouping is enabled" do
    @user.update!(preferences: { "show_split_grouped" => true })
    entry = create_transaction(name: "Grocery Store", amount: 100, account: @account)
    entry.split!([
      { name: "Food", amount: 60 },
      { name: "Household", amount: 40 }
    ])

    get account_url(@account)

    assert_response :success
    assert_select ".split-group", count: 1
    assert_select ".split-group" do
      assert_select "p", text: "Food", count: 0
    end
  end

  test "show renders split children as flat rows when grouping is disabled" do
    @user.update!(preferences: { "show_split_grouped" => false })
    entry = create_transaction(name: "Grocery Store", amount: 100, account: @account)
    entry.split!([
      { name: "Food", amount: 60 },
      { name: "Household", amount: 40 }
    ])

    get account_url(@account)

    assert_response :success
    assert_select ".split-group", count: 0
  end

  test "show avoids N+1 queries when loading split parents for grouped display" do
    @user.update!(preferences: { "show_split_grouped" => true })
    3.times do |i|
      entry = create_transaction(name: "Grocery Store #{i}", amount: 100, account: @account)
      entry.split!([
        { name: "Food", amount: 60 },
        { name: "Household", amount: 40 }
      ])
    end

    queries = capture_sql_queries { get account_url(@account) }
    assert_response :success

    # @split_parents loads all referenced split-parent entries in a single
    # `WHERE "entries"."id" IN (...)` query — a per-row `"id" = $1` lookup
    # would indicate the batching regressed into N+1.
    per_row_split_parent = queries.count { |q|
      q.match?(/FROM "entries".*WHERE.*"entries"\."id" = \$?\d+/) && !q.include?(" IN (")
    }
    assert_equal 0, per_row_split_parent, "N+1 per-row split-parent lookups detected (#{per_row_split_parent})"
  end

  test "show lazily loads statement tab data unless statements tab is active" do
    AccountStatement::Coverage.expects(:for_year).never
    AccountStatement.expects(:reconciliation_statuses_for).never

    get account_url(@account)

    assert_response :success
    assert_select "select[name='statement_year']", count: 0
    statements_path = account_path(@account, tab: "statements")
    assert_select "turbo-frame[src='#{statements_path}']"
  end

  test "statements tab links escape turbo frame for full-page navigation" do
    # Upload a statement to ensure table rows render
    statement = AccountStatement.create_from_upload!(
      family: @account.family,
      file: uploaded_file(
        filename: "test.pdf",
        content_type: "application/pdf",
        content: "%PDF-1.4 test content"
      ),
      account: @account
    )


    get account_url(@account, tab: "statements")

    assert_response :success

    # Inbox link escapes frame
    assert_select "a[href='#{account_statements_path}'][data-turbo-frame='_top']"

    # Statement filename link escapes frame
    assert_select "a[data-turbo-frame='_top']", text: statement.filename

    # Eye/view icon escapes frame and opens in new tab
    assert_select "a[target='_blank'][data-turbo-frame='_top'][aria-label='#{I18n.t("account_statements.table.view")}']"

    # Edit icon escapes frame
    assert_select "a[href='#{account_statement_path(statement)}'][data-turbo-frame='_top'][aria-label='#{I18n.t("account_statements.table.edit")}']"

    # Unlink button escapes frame
    assert_select "form[action='#{unlink_account_statement_path(statement)}'][data-turbo-frame='_top'] button"
  end

  test "statements tab shows coverage and upload for statement managers with account write access" do
    get account_url(@account, tab: "statements")

    assert_response :success
    assert_select "input[type=file][accept='.pdf,.csv,.xlsx']"
    assert_select "select[name='statement_year']"
    assert_select "p", text: I18n.l(Date.current.prev_month.beginning_of_month, format: "%b %Y")
  end

  test "statements tab lazy frame returns matching frame content" do
    frame_id = dom_id(@account, :statements_tab)

    get account_url(@account, tab: "statements"), headers: { "Turbo-Frame" => frame_id }

    assert_response :success
    assert_select "turbo-frame##{frame_id}", count: 1
    assert_select "select[name='statement_year']"
    assert_select "turbo-frame##{dom_id(@account, :container)}", count: 0
  end

  test "statements tab lists statements by period" do
    statements = [ Date.new(2024, 2, 1), Date.new(2024, 4, 1), Date.new(2024, 3, 1) ].map do |month|
      statement = AccountStatement.create_from_upload!(
        family: @account.family,
        account: @account,
        file: uploaded_file(filename: "statement_#{month}.csv", content_type: "text/csv", content: "date,amount\n#{month},1\n")
      )
      statement.update!(period_start_on: month, period_end_on: month.end_of_month)
      statement
    end

    get account_url(@account, tab: "statements")

    assert_response :success
    assert_equal statements.sort_by(&:period_end_on).reverse.map { |statement| dom_id(statement) },
                 css_select("tr[id^='account_statement_']").map { |row| row["id"] }
  end

  test "statements tab filters historical coverage by year" do
    account = Account.create!(
      family: @user.family,
      owner: @user,
      name: "Historical Checking",
      balance: 0,
      currency: "USD",
      accountable: Depository.new
    )
    statement = AccountStatement.create_from_upload!(
      family: @user.family,
      account: account,
      file: uploaded_file(filename: "historical.csv", content_type: "text/csv")
    )
    statement.update!(period_start_on: Date.new(2024, 2, 1), period_end_on: Date.new(2024, 2, 29))

    travel_to Date.new(2026, 5, 6) do
      get account_url(account, tab: "statements")

      assert_response :success
      assert_select "select[name='statement_year'] option[selected='selected']", text: "2026"
      assert_select "p", text: "May 2026"
      assert_select "p", text: "Not expected"

      get account_url(account, tab: "statements", statement_year: 2024)

      assert_response :success
      assert_select "select[name='statement_year'] option[selected='selected']", text: "2024"
      assert_select "p", text: "Jan 2024"
      assert_select "p", text: "Feb 2024"
      assert_select "p", text: "Covered"
      assert_select "p", text: "Missing"
      assert_select "p", text: "Not expected"
    end
  end

  test "statements tab hides upload for read only account access" do
    sign_in users(:family_member)

    get account_url(accounts(:credit_card), tab: "statements")

    assert_response :success
    assert_select "input[type=file]", count: 0
  end

  test "credit card page offers an overview tab" do
    sign_in users(:family_admin)

    get account_url(accounts(:credit_card))

    assert_response :success
    assert_select "[role=tab][data-id=overview]"
    assert_select "[role=tabpanel][data-id=overview]"
  end

  test "credit card overview renders the statement cycle" do
    sign_in users(:family_admin)
    card = accounts(:credit_card).credit_card
    card.update!(statement_close_day: 25, due_day: 5, minimum_payment: 25)
    accounts(:credit_card).entries.create!(
      name: "Cycle charge",
      date: Date.current.beginning_of_month + 9.days,
      amount: 100,
      currency: "USD",
      entryable: Transaction.new
    )

    materialize_balances(accounts(:credit_card))
    get account_url(accounts(:credit_card), tab: "overview")

    assert_response :success
    assert_match I18n.t("credit_cards.tabs.overview.statement_balance"), response.body
  end

  test "credit card overview hides the APR card when APR is blank" do
    sign_in users(:family_admin)
    accounts(:credit_card).credit_card.update!(statement_close_day: 25, due_day: 5, apr: nil, minimum_payment: nil)

    materialize_balances(accounts(:credit_card))
    get account_url(accounts(:credit_card), tab: "overview")

    assert_response :success
    assert_select "h4", text: I18n.t("credit_cards.tabs.overview.annual_percentage_rate"), count: 0
    assert_select "[data-testid='credit-card-summary-grid'][class*='sm:grid-cols-2']", count: 1
    assert_select "[data-testid='credit-card-summary-grid'][class*='@3xl:grid-cols-3']", count: 0
  end

  test "credit card overview shows the APR card when APR is present" do
    sign_in users(:family_admin)
    accounts(:credit_card).credit_card.update!(statement_close_day: 25, due_day: 5, apr: 18.99, minimum_payment: nil)

    materialize_balances(accounts(:credit_card))
    get account_url(accounts(:credit_card), tab: "overview")

    assert_response :success
    assert_select "h4", text: I18n.t("credit_cards.tabs.overview.annual_percentage_rate"), count: 1
    assert_select "[data-testid='credit-card-summary-grid'][class*='sm:grid-cols-2']", count: 1
    assert_select "[data-testid='credit-card-summary-grid'][class*='@3xl:grid-cols-3']", count: 1
  end

  test "credit card overview shows the estimated monthly interest for the APR" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26, apr: 12, minimum_payment: nil)

    travel_to Date.new(2026, 10, 16) do
      account.entries.create!(
        name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 1200, currency: "USD",
        entryable: Transaction.new
      )

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      assert_match I18n.t("credit_cards.tabs.overview.estimated_interest_label"), response.body
      assert_match I18n.t("credit_cards.tabs.overview.per_month", amount: Money.new(12, "USD").format), response.body
      assert_match I18n.t("credit_cards.tabs.overview.monthly_rate_label"), response.body
      assert_match I18n.t("credit_cards.tabs.overview.balance_carried_label"), response.body
      assert_match "1.000%", response.body
    end
  end

  test "credit card overview hides the minimum warning when minimum payment is blank" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26, minimum_payment: nil)

    travel_to Date.new(2026, 10, 16) do
      account.entries.create!(
        name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 100, currency: "USD",
        entryable: Transaction.new
      )

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      assert_no_match "This statement came to", response.body
    end
  end

  test "credit card overview shows the remaining amount and partial status" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26)

    travel_to Date.new(2026, 10, 16) do
      account.entries.create!(
        name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 100, currency: "USD",
        entryable: Transaction.new
      )
      account.entries.create!(
        name: "Card payment", date: Date.new(2026, 10, 12), amount: -40, currency: "USD",
        entryable: Transaction.new
      )

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      # The bill card shows what is still owed on the statement: 100 less the 40 paid.
      # Scoped to that card, since the APR card also renders a balance.
      bill_card = Nokogiri::HTML(response.body)
        .css("[data-testid=credit-card-summary-grid] > div:first-child")
        .first
      assert_includes bill_card.text, Money.new(60, "USD").format
      assert_match I18n.t("credit_cards.tabs.overview.status_partial"), response.body
    end
  end

  test "credit card overview shows the cycle breakdown and next close" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26)

    travel_to Date.new(2026, 10, 16) do
      account.entries.create!(
        name: "Cycle charge", date: Date.new(2026, 10, 12), amount: 100, currency: "USD",
        entryable: Transaction.new
      )
      account.entries.create!(
        name: "Card payment", date: Date.new(2026, 10, 14), amount: -40, currency: "USD",
        entryable: Transaction.new
      )

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      assert_match I18n.t("credit_cards.tabs.overview.charges"), response.body
      assert_match I18n.t("credit_cards.tabs.overview.payments_applied"), response.body
      assert_match Money.new(100, "USD").format, response.body
      assert_match Money.new(40, "USD").format, response.body
      assert_match I18n.t("credit_cards.tabs.overview.closes_on_days", date: I18n.l(Date.new(2026, 11, 10), format: :long), count: 25), response.body
    end
  end

  test "credit card overview shows the next open scheduled card payment" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26)

    travel_to Date.new(2026, 10, 16) do
      series = account.inbound_recurring_transfers.create!(
        family: account.family,
        account: accounts(:depository),
        name: "Card payment",
        amount: 40,
        currency: "USD",
        expected_day_of_month: 24,
        last_occurrence_date: Date.new(2026, 9, 24),
        next_expected_date: Date.new(2026, 10, 24),
        manual: true
      )
      open_due = series.recurring_occurrences.open_status.minimum(:due_on)

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      assert_match I18n.t(
        "credit_cards.tabs.overview.scheduled_payment",
        amount: Money.new(40, "USD").format,
        date: I18n.l(open_due, format: :long)
      ), response.body
    end
  end

  test "credit card overview hides a scheduled payment from a member without its source" do
    sign_in users(:family_member)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26)
    account.inbound_recurring_transfers.create!(
      family: account.family,
      account: accounts(:investment),
      name: "Card payment",
      amount: 40,
      currency: "USD",
      expected_day_of_month: 24,
      last_occurrence_date: 2.months.ago.to_date,
      next_expected_date: 1.month.from_now.to_date,
      bill_type: "transfer",
      manual: true
    )

    materialize_balances(account)
    get account_url(account, tab: "overview")

    assert_response :success
    assert_no_match "Scheduled payment", response.body
  end

  test "credit card overview highlights an overdue statement" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 5, due_day: 21)

    travel_to Date.new(2026, 10, 30) do
      account.entries.create!(
        name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 552, currency: "USD",
        entryable: Transaction.new
      )

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      assert_select "span.text-destructive", text: I18n.t("credit_cards.tabs.overview.due_overdue_days", date: I18n.l(Date.new(2026, 10, 21), format: :long), count: 9)
    end
  end

  test "credit card overview shows the payment due this month for an early close day" do
    sign_in users(:family_admin)
    accounts(:credit_card).credit_card.update!(statement_close_day: 10, due_day: 26)

    # A card closing on the 10th and due on the 26th, read on the 16th. The
    # bill due is the statement that closed on the 10th, which falls on the 26th
    # of THIS month -- not the 26th of next, which is the statement still
    # building and not yet owed.
    travel_to Date.new(2026, 10, 16) do
      materialize_balances(accounts(:credit_card))
      get account_url(accounts(:credit_card), tab: "overview")

      assert_response :success
      assert_match I18n.l(Date.new(2026, 10, 26), format: :long), response.body
      assert_match I18n.t("credit_cards.tabs.overview.due_on_days", date: I18n.l(Date.new(2026, 10, 26), format: :long), count: 10), response.body
    end
  end

  test "credit card overview reads a negative since-statement balance as a credit" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26)

    travel_to Date.new(2026, 10, 16) do
      account.entries.create!(
        name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 100, currency: "USD",
        entryable: Transaction.new
      )
      account.entries.create!(
        name: "Payment after the close", date: Date.new(2026, 10, 12), amount: -250, currency: "USD",
        entryable: Transaction.new
      )

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      assert_match I18n.t("credit_cards.tabs.overview.credit_toward_next"), response.body
    end
  end

  test "credit card overview shows the credit label when a credit outlives the due date" do
    sign_in users(:family_admin)
    account = accounts(:credit_card)
    account.credit_card.update!(statement_close_day: 10, due_day: 26)

    # Read after the 26th: the due date has rolled to the statement still
    # building, and the cardholder has paid down more than that statement has
    # accrued. The credit is the fact worth stating; a due date here would
    # promise a payment the credit may cancel.
    travel_to Date.new(2026, 10, 30) do
      account.entries.create!(
        name: "Cycle charge", date: Date.new(2026, 9, 20), amount: 100, currency: "USD",
        entryable: Transaction.new
      )
      account.entries.create!(
        name: "Payment after the close", date: Date.new(2026, 10, 12), amount: -250, currency: "USD",
        entryable: Transaction.new
      )

      materialize_balances(account)
      get account_url(account, tab: "overview")

      assert_response :success
      assert_match I18n.t("credit_cards.tabs.overview.credit_toward_next"), response.body
      assert_no_match I18n.l(Date.new(2026, 11, 26), format: :long), response.body
    end
  end

  test "credit card overview asks for a cycle when none is set" do
    sign_in users(:family_admin)

    materialize_balances(accounts(:credit_card))
    get account_url(accounts(:credit_card), tab: "overview")

    assert_response :success
    assert_match I18n.t("credit_cards.tabs.overview.no_cycle_title"), response.body
  end

  test "account activity marks trade amounts as privacy-sensitive" do
    trade_entry = entries(:trade)
    expected_amount = ApplicationController.helpers.format_money(-trade_entry.amount_money)

    get account_url(accounts(:investment))

    assert_response :success
    assert_select "turbo-frame##{dom_id(trade_entry)} p.privacy-sensitive", text: expected_amount, count: 1
  end

  test "account activity keeps excluded entries visible so they can be restored" do
    trade_entry = entries(:trade)
    trade_entry.update!(excluded: true)

    get account_url(accounts(:investment))

    assert_response :success
    assert_select "turbo-frame##{dom_id(trade_entry)}"
  end

  test "renders investment account with gains chart view" do
    get account_url(accounts(:investment), chart_view: "gains")

    assert_response :success
    assert_select "option[value=gains][selected]"
    assert_select "p", text: I18n.t("UI.account.chart.title.total_gains")
  end

  # The chart and the Schedule tab's forecast card read one projection. The
  # chart used to build one and the Schedule partial a second, for the same
  # date, on every render of a loan's page.
  test "a loan account page builds its payoff projection once for the chart and the Schedule tab" do
    loan_account = accounts(:loan)
    projection = loan_account.loan.payoff_projection(as_of: Date.current)
    Loan.any_instance.expects(:payoff_projection).once.returns(projection)

    get account_url(loan_account)

    assert_response :success
    assert_includes response.body, I18n.t("loans.tabs.schedule.forecasted_payoff_date")
  end

  test "remembers selected per_page across account navigation" do
    other_account = accounts(:credit_card)

    get account_url(@account, per_page: 50)
    assert_response :success
    assert_select "select[name='per_page'] option[value='50'][selected]"

    get account_url(other_account)
    assert_response :success
    assert_select "select[name='per_page'] option[value='50'][selected]"
  end

  test "shares remembered per_page with the global transactions page" do
    get transactions_url(per_page: 100)
    assert_response :success

    get account_url(@account)
    assert_response :success
    assert_select "select[name='per_page'] option[value='100'][selected]"
  end

  test "shares account per_page preference with the global transactions page" do
    get account_url(@account, per_page: 50)
    assert_response :success

    get transactions_url
    assert_response :redirect
    follow_redirect!
    assert_response :success
    assert_select "select[name='per_page'] option[value='50'][selected]"
  end

  test "falls back to default per_page when nothing was stored yet" do
    get account_url(@account)
    assert_response :success
    assert_select "select[name='per_page'] option[value='10'][selected]"
  end

  test "activity pagination keeps activity tab when loaded from holdings tab" do
    investment = accounts(:investment)

    11.times do |i|
      Entry.create!(
        account: investment,
        name: "Test investment activity #{i}",
        date: Date.current - i.days,
        amount: 10 + i,
        currency: investment.currency,
        entryable: Transaction.new
      )
    end

    get account_url(investment, tab: "holdings")

    assert_response :success
    assert_select "a[href*='page=2'][href*='tab=activity']"
    assert_select "a[href*='page=2'][href*='tab=holdings']", count: 0
  end

  test "account activity constrains long category labels before the amount on wide screens" do
    category = categories(:food_and_drink)
    category.update!(name: "Super Long Category Name That Should Stop Before The Amount On Wide Screens Too")

    entry = @account.entries.create!(
      name: "Wide category verification",
      date: Date.current,
      amount: 187.65,
      currency: @account.currency,
      entryable: Transaction.new(category: category)
    )

    get account_url(@account, tab: "activity")

    assert_response :success
    assert_select "##{dom_id(entry.entryable, "category_menu_desktop")}"
    assert_select "##{dom_id(entry.entryable, "category_menu_desktop")}.min-w-0"
    assert_select "##{dom_id(entry.entryable, "category_menu_desktop")}.overflow-hidden"
    assert_select "##{dom_id(entry.entryable, "category_menu_desktop")} button.block"
    assert_select "##{dom_id(entry.entryable, "category_menu_desktop")} button.w-full"
    assert_select "##{dom_id(entry.entryable, "category_menu_desktop")} button.overflow-hidden"
    assert_select "##{dom_id(entry.entryable, "category_menu_desktop")} [data-testid='category-name']"
    assert_select "div.hidden.md\\:flex.min-w-0"
  end

  test "should sync account" do
    post sync_account_url(@account)
    assert_redirected_to account_url(@account)
  end

  test "should get sparkline" do
    get sparkline_account_url(@account)
    assert_response :success
  end

  test "sparkline stays fresh when another account syncs" do
    get sparkline_account_url(@account)
    etag = response.headers["ETag"]

    @account.family.touch(:latest_sync_completed_at)
    get sparkline_account_url(@account), headers: { "If-None-Match" => etag }

    assert_response :not_modified
  end

  test "sparkline is re-rendered when the account's balances change" do
    Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
    get sparkline_account_url(@account)
    etag = response.headers["ETag"]
    before = response.body

    travel 1.minute do
      @account.balances.create!(date: 3.days.ago.to_date, balance: 1234, start_cash_balance: 1234, currency: @account.currency)
      get sparkline_account_url(@account), headers: { "If-None-Match" => etag }
    end

    assert_response :success
    assert_not_equal before, response.body
  end

  test "sparkline is re-rendered after the account's own sync completes" do
    get sparkline_account_url(@account)
    etag = response.headers["ETag"]

    travel 1.minute do
      @account.syncs.create!(status: "completed", completed_at: Time.current)
      get sparkline_account_url(@account), headers: { "If-None-Match" => etag }
    end

    assert_response :success
  end

  # AccountProvider rows don't touch the account, and swapping one keeps it linked.
  test "sparkline is re-rendered when the account's provider link changes" do
    AccountProvider.create!(account: @account, provider: plaid_accounts(:one))
    get sparkline_account_url(@account)
    etag = response.headers["ETag"]

    travel 1.minute do
      @account.account_providers.destroy_all
      other = PlaidAccount.create!(
        plaid_item: plaid_items(:one), plaid_id: "acc_mock_swap", name: "Swapped", plaid_type: "depository",
        currency: "USD", current_balance: 1
      )
      AccountProvider.create!(account: @account, provider: other)
      get sparkline_account_url(@account), headers: { "If-None-Match" => etag }
    end

    assert_response :success
  end

  test "an investment sparkline is re-rendered after any family sync" do
    investment = accounts(:investment)
    get sparkline_account_url(investment)
    etag = response.headers["ETag"]

    travel 1.minute do
      investment.family.touch(:latest_sync_completed_at)
      get sparkline_account_url(investment), headers: { "If-None-Match" => etag }
    end

    assert_response :success
  end

  test "sidebar sparkline URLs carry a version the browser may reuse" do
    get account_url(@account)

    [ sidebar_sparkline_src(dom_id(@account, :sparkline)), sidebar_sparkline_src("depository_sparkline") ].each do |src|
      assert_match(/[?&]v=\h{16}\z/, src)
      get src
      assert_response :success
      assert_includes response.headers["Cache-Control"], "max-age=86400"
    end
  end

  test "a sparkline URL with an outdated version must be revalidated" do
    get sparkline_account_url(@account, v: "outdated")
    assert_response :success
    assert_includes response.headers["Cache-Control"], "max-age=0"

    get accountable_sparkline_url("depository", v: "outdated")
    assert_response :success
    assert_includes response.headers["Cache-Control"], "max-age=0"
  end

  test "a sidebar sparkline URL changes when the account's balances do" do
    get account_url(@account)
    before = sidebar_sparkline_src(dom_id(@account, :sparkline))

    travel 1.minute do
      @account.balances.create!(date: 40.days.ago.to_date, balance: 1, currency: @account.currency)
      get account_url(@account)
    end

    assert_not_equal before, sidebar_sparkline_src(dom_id(@account, :sparkline))
  end

  test "sidebar sparkline URLs change the next day" do
    get account_url(@account)
    before = [ sidebar_sparkline_src(dom_id(@account, :sparkline)), sidebar_sparkline_src("depository_sparkline") ]

    travel 1.day do
      get account_url(@account)
      after = [ sidebar_sparkline_src(dom_id(@account, :sparkline)), sidebar_sparkline_src("depository_sparkline") ]

      assert_not_equal before[0], after[0]
      assert_not_equal before[1], after[1]
    end
  end

  test "sparkline renders an empty series without a trend" do
    empty_series = Series.new(
      start_date: 1.day.ago.to_date,
      end_date: Date.current,
      interval: "1 day",
      values: []
    )
    Account.any_instance.expects(:sparkline_series).returns(empty_series)

    get sparkline_account_url(@account)

    assert_response :success
    assert_select "p.font-mono", count: 0
  end

  test "destroys account" do
    delete account_url(@account)
    assert_redirected_to accounts_path
    assert_enqueued_with job: DestroyJob
    assert_equal "Depository account scheduled for deletion", flash[:notice]
  end

  test "destroy reports failure and keeps the account listed when the enqueue raises" do
    DestroyJob.queue_adapter.stubs(:enqueue).raises(RedisClient::CannotConnectError, "Connection refused")

    delete account_url(@account)

    assert_redirected_to accounts_path
    assert_equal I18n.t("accounts.destroy.failed"), flash[:alert]
    assert_equal "active", @account.reload.status

    get accounts_url
    assert_select "turbo-frame##{dom_id(@account)}"
  end

  test "destroy reports failure when the enqueue is rejected" do
    DestroyJob.queue_adapter.stubs(:enqueue).raises(ActiveJob::EnqueueError, "rejected")

    delete account_url(@account)

    assert_redirected_to accounts_path
    assert_equal I18n.t("accounts.destroy.failed"), flash[:alert]
    assert_nil flash[:notice]
    assert_equal "active", @account.reload.status
  end

  # The second request of a double submit finds the account already pending
  # deletion. It reports failure rather than erroring, enqueues nothing more,
  # and leaves the first request's mark in place.
  test "a second destroy of an account pending deletion reports failure" do
    delete account_url(@account)
    assert_equal "pending_deletion", @account.reload.status

    assert_no_enqueued_jobs(only: DestroyJob) do
      delete account_url(@account)
    end

    assert_redirected_to accounts_path
    assert_equal I18n.t("accounts.destroy.failed"), flash[:alert]
    assert_equal "pending_deletion", @account.reload.status
  end

  test "syncing linked account triggers sync for all provider items" do
    plaid_account = plaid_accounts(:one)
    AccountProvider.create!(account: @account, provider: plaid_account)

    # Reload to ensure the account has the provider association loaded
    @account.reload

    # Mock at the class level since controller loads account from DB
    Account.any_instance.expects(:syncing?).returns(false)
    PlaidItem.any_instance.expects(:syncing?).returns(false)
    PlaidItem.any_instance.expects(:sync_later_with_provider_refresh).once

    post sync_account_url(@account)
    assert_redirected_to account_url(@account)
  end

  test "syncing unlinked account calls account sync_later" do
    Account.any_instance.expects(:syncing?).returns(false)
    Account.any_instance.expects(:sync_later).once

    post sync_account_url(@account)
    assert_redirected_to account_url(@account)
  end

  test "confirms unlink for linked account" do
    plaid_account = plaid_accounts(:one)
    AccountProvider.create!(account: @account, provider: plaid_account)

    get confirm_unlink_account_url(@account)
    assert_response :success
  end

  test "redirects when confirming unlink for unlinked account" do
    get confirm_unlink_account_url(@account)
    assert_redirected_to account_url(@account)
    assert_equal "Account is not linked to a provider", flash[:alert]
  end

  test "unlinks linked account successfully with new system" do
    plaid_account = plaid_accounts(:one)
    AccountProvider.create!(account: @account, provider: plaid_account)
    @account.reload

    assert @account.linked?

    delete unlink_account_url(@account)
    @account.reload

    assert_not @account.linked?
    assert_redirected_to accounts_path
    assert_equal "Account unlinked successfully. It is now a manual account.", flash[:notice]
  end

  test "unlinks linked account successfully with legacy system" do
    plaid_account = plaid_accounts(:one)
    @account.update!(plaid_account_id: plaid_account.id)
    @account.reload

    assert @account.linked?

    delete unlink_account_url(@account)
    @account.reload

    assert_not @account.linked?
    assert_nil @account.plaid_account_id
    assert_redirected_to accounts_path
    assert_equal "Account unlinked successfully. It is now a manual account.", flash[:notice]
  end

  test "redirects when unlinking unlinked account" do
    delete unlink_account_url(@account)
    assert_redirected_to account_url(@account)
    assert_equal "Account is not linked to a provider", flash[:alert]
  end

  test "unlinked account can be deleted" do
    plaid_account = plaid_accounts(:one)
    AccountProvider.create!(account: @account, provider: plaid_account)
    @account.reload

    # Cannot delete while linked
    delete account_url(@account)
    assert_redirected_to account_url(@account)
    assert_equal "Cannot delete a linked account. Please unlink it first.", flash[:alert]

    # Unlink the account
    delete unlink_account_url(@account)
    @account.reload

    # Now can delete
    delete account_url(@account)
    assert_redirected_to accounts_path
    assert_enqueued_with job: DestroyJob
    assert_equal "Depository account scheduled for deletion", flash[:notice]
  end

  test "disabling an account keeps it visible on index" do
    @account.disable!

    get accounts_path

    assert_response :success
    assert_includes @response.body, @account.name
  end

  test "toggle_active disables and re-enables an account" do
    patch toggle_active_account_url(@account)
    assert_redirected_to accounts_path
    @account.reload
    assert @account.disabled?

    patch toggle_active_account_url(@account)
    assert_redirected_to accounts_path
    @account.reload
    assert @account.active?
  end

  test "toggle_exclude_from_reports toggles the flag on an account" do
    assert_not @account.exclude_from_reports?

    patch toggle_exclude_from_reports_account_url(@account)
    assert_redirected_to accounts_path
    @account.reload
    assert @account.exclude_from_reports?

    patch toggle_exclude_from_reports_account_url(@account)
    assert_redirected_to accounts_path
    @account.reload
    assert_not @account.exclude_from_reports?
  end

  test "toggle_exclude_from_reports requires write permission" do
    sign_in users(:family_member)

    patch toggle_exclude_from_reports_account_url(accounts(:credit_card))
    assert_redirected_to account_url(accounts(:credit_card))
  end

  test "logo_options shows the icons found and Brandfetch inside the logo frame without saving" do
    Setting.stubs(:brand_fetch_client_id).returns("test-client-id")
    @account.update!(institution_domain: "krungsri.com")
    @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "krungsri.com.png",
                         metadata: { "logo_source" => "yandex", "logo_key" => "yandex", "logo_auto" => true })
    icons = [ logo_icon("appstore:123", "appstore", 512, name: "krungsri"),
              logo_icon("yandex", "yandex", 120, body: file_fixture("square-placeholder.png").binread) ]
    Account::LogoFetcher.any_instance.stubs(:candidates).returns(icons)

    get logo_options_account_url(@account), headers: { "Turbo-Frame" => dom_id(@account, :logo_field) }

    assert_response :success
    assert_select "turbo-frame##{dom_id(@account, :logo_field)}"
    assert_select "button[type=button][data-account-logo-picker-choice-param='appstore:123'][title=krungsri]"
    assert_select "button[type=button][data-account-logo-picker-choice-param=brandfetch]"
    assert_select "button[type=button][data-account-logo-picker-choice-param]", 2, "the current icon only resets the choice"
    assert_select "button[type=submit]:not([form])", 0, "choosing an icon saves nothing"
    assert_select "img[src^='data:image/png;base64,']", 2
  end

  test "logo_options searches the domain typed in the form without saving it" do
    @account.update!(institution_domain: "tbank.ru")
    Account::LogoFetcher.expects(:new).with { |account| account.institution_domain == "krungsri.com" && account.institution_name == "Krungsri" }
      .returns(stub(candidates: []))

    get logo_options_account_url(@account), params: { institution_domain: "https://www.krungsri.com/", institution_name: "Krungsri" },
                                            headers: { "Turbo-Frame" => dom_id(@account, :logo_field) }

    assert_response :success
    assert_equal "tbank.ru", @account.reload.institution_domain
  end

  test "logo_options for a new account searches the typed domain" do
    Account::LogoFetcher.expects(:new).with { |account| account.new_record? && account.institution_domain == "krungsri.com" }
      .returns(stub(candidates: []))

    get logo_options_accounts_url, params: { institution_domain: "krungsri.com", institution_name: "Krungsri" },
                                   headers: { "Turbo-Frame" => "logo_field_account" }

    assert_response :success
    assert_select "turbo-frame#logo_field_account"
  end

  test "logo_options keeps an icon selectable when its source now serves a different image" do
    @account.update!(institution_domain: "krungsri.com")
    @account.logo.attach(io: file_fixture("square-placeholder.png").open, filename: "krungsri.com.png",
                         metadata: { "logo_source" => "yandex", "logo_key" => "yandex", "logo_auto" => true })
    Account::LogoFetcher.any_instance.stubs(:candidates).returns([ logo_icon("yandex", "yandex", 120) ])

    get logo_options_account_url(@account), headers: { "Turbo-Frame" => dom_id(@account, :logo_field) }

    assert_select "button[data-account-logo-picker-choice-param=yandex]"
  end

  test "logo_options outside the frame goes to the account" do
    get logo_options_account_url(@account)

    assert_redirected_to account_url(@account)
  end

  test "logo_options requires write permission" do
    sign_in users(:family_member)

    get logo_options_account_url(accounts(:credit_card))
    assert_redirected_to account_url(accounts(:credit_card))
  end

  test "select_provider shows available providers" do
    get select_provider_account_url(@account)
    assert_response :success
  end

  test "set_default sets user default account" do
    patch set_default_account_url(@account)
    assert_redirected_to accounts_path
    @user.reload
    assert_equal @account.id, @user.default_account_id
  end

  test "set_default rejects ineligible account type" do
    investment = accounts(:investment)

    patch set_default_account_url(investment)
    assert_redirected_to accounts_path
    assert_equal I18n.t("accounts.set_default.depository_only"), flash[:alert]

    @user.reload
    assert_not_equal investment.id, @user.default_account_id
  end

  test "remove_default clears user default account" do
    @user.update!(default_account: @account)

    patch remove_default_account_url(@account)
    assert_redirected_to accounts_path

    @user.reload
    assert_nil @user.default_account_id
  end

  test "select_provider redirects for already linked account" do
    plaid_account = plaid_accounts(:one)
    AccountProvider.create!(account: @account, provider: plaid_account)

    get select_provider_account_url(@account)
    assert_redirected_to account_url(@account)
    assert_equal "Account is already linked to a provider", flash[:alert]
  end

  test "unlink preserves SnaptradeAccount record" do
    snaptrade_account = snaptrade_accounts(:fidelity_401k)
    investment = accounts(:investment)
    AccountProvider.create!(account: investment, provider: snaptrade_account)
    investment.reload

    assert investment.linked?

    delete unlink_account_url(investment)
    investment.reload

    assert_not investment.linked?
    assert_redirected_to accounts_path
    # SnaptradeAccount should still exist (not destroyed)
    assert SnaptradeAccount.exists?(snaptrade_account.id), "SnaptradeAccount should be preserved after unlink"
    # But AccountProvider should be gone
    assert_not AccountProvider.exists?(provider_type: "SnaptradeAccount", provider_id: snaptrade_account.id)
  end

  test "unlink does not enqueue SnapTrade cleanup job" do
    snaptrade_account = snaptrade_accounts(:fidelity_401k)
    investment = accounts(:investment)
    AccountProvider.create!(account: investment, provider: snaptrade_account)
    investment.reload

    assert_no_enqueued_jobs(only: SnaptradeConnectionCleanupJob) do
      delete unlink_account_url(investment)
    end
  end

  test "unlink detaches holdings from SnapTrade provider" do
    snaptrade_account = snaptrade_accounts(:fidelity_401k)
    investment = accounts(:investment)
    ap = AccountProvider.create!(account: investment, provider: snaptrade_account)

    # Assign a holding to this provider
    holding = holdings(:one)
    holding.update!(account_provider: ap)

    delete unlink_account_url(investment)
    holding.reload

    assert_nil holding.account_provider_id, "Holding should be detached from provider after unlink"
  end

  # Regression for #2516: the account sidebar fragment cache renders DS::* view
  # components, which Rails' ERB dependency tracker mis-parses as a bogus "Ds/D"
  # template dependency. With automatic digesting enabled that logged
  # "Couldn't find template for digesting: Ds/D" on every cache miss. The
  # fragment is manually versioned and opts out of digesting via skip_digest.
  test "sidebar fragment cache does not log a bogus template digest error" do
    log = StringIO.new
    logger = ActiveSupport::Logger.new(log)

    original_perform_caching = ActionController::Base.perform_caching
    original_view_logger = ActionView::Base.logger
    original_rails_logger = Rails.logger

    ActionController::Base.perform_caching = true
    ActionView::Base.logger = logger
    Rails.logger = logger

    get accounts_path
    assert_response :success
    assert_no_match(/Couldn't find template for digesting/, log.string)
  ensure
    ActionController::Base.perform_caching = original_perform_caching
    ActionView::Base.logger = original_view_logger
    Rails.logger = original_rails_logger
  end

  # --- member-owned connections (issue #3579) ------------------------------

  test "an owner is not shown a connection carrying an account they cannot see" do
    # Ownership must not widen exposure: the card renders the item's accounts
    # unfiltered (and is re-rendered by a viewer-less broadcast), so the whole
    # card is withheld rather than shown with a filtered list.
    member = users(:family_member)
    family = families(:dylan_family)
    item = PlaidItem.create!(
      family: family, plaid_id: "item_card_#{SecureRandom.hex(4)}",
      access_token: "token", name: "Owned Bank", owner: member
    )
    hidden = Account.create!(
      family: family, owner: users(:family_admin), name: "Not Shared With Member",
      balance: 100, currency: "USD", accountable: Depository.new
    )
    hidden.account_shares.destroy_all
    plaid_account = PlaidAccount.create!(
      plaid_item: item, name: "Hidden Feed", plaid_id: "acct_card_#{SecureRandom.hex(4)}",
      plaid_type: "depository", plaid_subtype: "checking", currency: "USD",
      current_balance: 100, available_balance: 100
    )
    AccountProvider.create!(account: hidden, provider: plaid_account)

    sign_in member
    get accounts_url

    assert_response :success
    assert_select "##{ActionView::RecordIdentifier.dom_id(item)}", count: 0
    assert_no_match(/Not Shared With Member/, response.body)
  end

  test "an owner is shown their freshly connected item before it has any accounts" do
    # The case ownership visibility exists for: just connected, nothing synced.
    member = users(:family_member)
    item = PlaidItem.create!(
      family: families(:dylan_family), plaid_id: "item_fresh_#{SecureRandom.hex(4)}",
      access_token: "token", name: "Fresh Bank", owner: member
    )

    sign_in member
    get accounts_url

    assert_response :success
    assert_select "##{ActionView::RecordIdentifier.dom_id(item)}", count: 1
  end


  test "an owner sees the management controls on their own connection card" do
    member = users(:family_member)
    item = PlaidItem.create!(
      family: families(:dylan_family), plaid_id: "item_ctrl_#{SecureRandom.hex(4)}",
      access_token: "token", name: "Controls Bank", owner: member
    )

    sign_in member
    get accounts_url

    assert_response :success
    assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 1
  end

  test "a member demoted to guest loses the controls on a connection they own" do
    member = users(:family_member)
    item = PlaidItem.create!(
      family: families(:dylan_family), plaid_id: "item_demote_#{SecureRandom.hex(4)}",
      access_token: "token", name: "Demoted Bank", owner: member
    )
    member.update!(role: :guest)

    sign_in member
    get accounts_url

    assert_response :success
    assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 0
  end

  test "a member sees no controls on a connection someone else owns" do
    item = PlaidItem.create!(
      family: families(:dylan_family), plaid_id: "item_noctrl_#{SecureRandom.hex(4)}",
      access_token: "token", name: "Admin Bank", owner: users(:family_admin)
    )

    sign_in users(:family_member)
    get accounts_url

    assert_response :success
    assert_select "a[href=?]", edit_plaid_item_path(item, add_accounts: true), count: 0
  end

  test "reorder saves the manual order of one account group" do
    # Same shape as the sidebar's sortable-list: group in the URL, ids in the body.
    patch reorder_accounts_url(group: "depository"), params: { account_ids: [ accounts(:connected).id, @account.id ] }, as: :json

    assert_response :success
    assert_equal [ accounts(:connected).id, @account.id ], @user.reload.manual_account_order["depository"]
  end

  test "reorder drops accounts from another family" do
    foreign = families(:empty).accounts.create!(name: "Foreign", currency: "USD", balance: 0, accountable: Depository.new, owner: users(:empty))

    patch reorder_accounts_url, params: { group: "depository", account_ids: [ foreign.id, @account.id ] }, as: :json

    assert_response :success
    assert_equal [ @account.id ], @user.reload.manual_account_order["depository"]
  end

  test "reorder rejects an unknown group" do
    patch reorder_accounts_url, params: { group: "not_a_type", account_ids: [ @account.id ] }, as: :json

    assert_response :unprocessable_entity
    assert_nil @user.reload.manual_account_order["not_a_type"]
  end

  test "sidebar shows drag handles only with the manual account order" do
    get account_url(@account)
    assert_select "[data-controller~='sortable-list']", count: 0

    @user.update!(default_account_order: "manual")
    get account_url(@account)
    assert_select "[data-controller~='sortable-list'][data-sortable-list-url-value=?]", reorder_accounts_path(group: "depository")
    assert_select "[data-sortable-list-target='item'][data-sortable-list-id=?]", @account.id
  end

  private
    # A manual (unsynced) account with no entries, so counts stay exact.
    def create_manual_account
      @user.family.accounts.create!(
        name: "Manual test account",
        balance: 100,
        currency: "USD",
        accountable: Depository.new
      )
    end

    def sidebar_sparkline_src(frame_id)
      css_select("turbo-frame##{frame_id}").first["src"]
    end

    def logo_icon(key, source, size, name: nil, body: "\x89PNG".b)
      Account::LogoFetcher::Icon.new(key:, source:, name:, body:, size:, content_type: "image/png", extension: "png")
    end

    # The Overview reads the account's balance records, which sync builds from
    # the entries. Tests build them after creating entries directly.
    def materialize_balances(account)
      Balance::Materializer.new(account, strategy: :forward).materialize_balances
    end

    # Lucide SVGs carry no icon-name class, so an icon is identified by its path data.
    def eye_off_icon_paths
      Nokogiri::HTML::DocumentFragment.parse(ApplicationController.helpers.icon("eye-off")).css("path").map { |path| path["d"] }
    end

    # #3630. Links a shared and an unshared account to +item+ through two fresh
    # provider rows built by the block, and returns them in that order. Shares
    # are reset first so the member's access is exactly the one granted here.
    def link_two_accounts_to(item)
      admin = users(:family_admin)
      member = users(:family_member)
      shared = accounts(:depository)
      unshared = accounts(:investment)
      unshared.update!(name: "Unshared Brokerage 235")

      [ shared, unshared ].each_with_index do |account, index|
        account.update!(owner: admin)
        account.account_shares.destroy_all
        AccountProvider.create!(account: account, provider: yield(item, index))
      end
      shared.account_shares.create!(user: member, permission: "read_only")

      [ shared, unshared ]
    end
end

class AccountsControllerSimplefinCtaTest < ActionDispatch::IntegrationTest
  fixtures :users, :families

  setup do
    sign_in users(:family_admin)
    @family = families(:dylan_family)
  end

  test "when unlinked SFAs exist and manuals exist, shows setup button only" do
    item = SimplefinItem.create!(family: @family, name: "Conn", access_url: "https://example.com/access")
    # Unlinked SFA (no account and no provider link)
    item.simplefin_accounts.create!(name: "A", account_id: "sf_a", currency: "USD", current_balance: 1, account_type: "depository")
    # One manual account available
    Account.create!(family: @family, name: "Manual A", currency: "USD", balance: 0, accountable_type: "Depository", accountable: Depository.create!(subtype: "checking"))

    get accounts_path
    assert_response :success
    # Expect setup link present
    assert_includes @response.body, setup_accounts_simplefin_item_path(item)
    # Relink modal (SimpleFin-specific) should not be present anymore
    refute_includes @response.body, "Link existing accounts"
  end

  test "when SFAs exist and none unlinked and manuals exist, no relink modal is shown (unified flow)" do
    item = SimplefinItem.create!(family: @family, name: "Conn2", access_url: "https://example.com/access")
    # Create a manual linked to SFA so unlinked count == 0
    sfa = item.simplefin_accounts.create!(name: "B", account_id: "sf_b", currency: "USD", current_balance: 1, account_type: "depository")
    linked = Account.create!(family: @family, name: "Linked", currency: "USD", balance: 0, accountable_type: "Depository", accountable: Depository.create!(subtype: "savings"))
    # Legacy association sufficient to count as linked
    sfa.update!(account: linked)

    # Also create another manual account to make manuals_exist true
    Account.create!(family: @family, name: "Manual B", currency: "USD", balance: 0, accountable_type: "Depository", accountable: Depository.create!(subtype: "checking"))

    get accounts_path
    assert_response :success
    # The SimpleFin-specific relink modal is removed in favor of unified provider flow
    refute_includes @response.body, "Link existing accounts"
  end

  test "when no SFAs exist, shows neither CTA" do
    item = SimplefinItem.create!(family: @family, name: "Conn3", access_url: "https://example.com/access")

    get accounts_path
    assert_response :success
    refute_includes @response.body, setup_accounts_simplefin_item_path(item)
    refute_includes @response.body, "Link existing accounts"
  end
end