Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
39.8 KB
Raw Blame
require "test_helper"

class FamilyTest < ActiveSupport::TestCase
  include SyncableInterfaceTest
  include SqlQueryCapture

  def setup
    @syncable = families(:dylan_family)
  end

  # The foreign key refuses to delete a statement an import carries, so a
  # family's imports must go before its statements.
  test "destroys a family whose import carries a statement" do
    family = Family.create!(name: "Statements", currency: "USD")
    statement = AccountStatement.create_from_upload!(
      family: family,
      account: nil,
      file: uploaded_file(filename: "statement.csv", content_type: "text/csv", content: "date,amount\n2024-01-01,1\n")
    )
    import = TransactionImport.create!(family: family, account_statement: statement)

    family.destroy!

    assert_not Family.exists?(family.id)
    assert_not AccountStatement.exists?(statement.id)
    assert_not Import.exists?(import.id)
  end

  test "missing_data_provider? is false under the keyless securities fallback" do
    family = Family.create!(name: "Fallback", currency: "USD")
    account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)
    trade = Trade.new(security: securities(:aapl), qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy")
    account.entries.create!(name: "Buy AAPL", date: 1.day.ago.to_date, amount: 100, currency: "USD", entryable: trade)

    yahoo = mock("yahoo_finance")
    yahoo.stubs(:class).returns(Provider::YahooFinance)
    Provider::Registry.stubs(:yahoo_finance).returns(yahoo)
    Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])
    Setting.stubs(:twelve_data_api_key).returns(nil)

    with_env_overrides("TWELVE_DATA_API_KEY" => nil) do
      assert family.requires_securities_data_provider?
      assert_not family.requires_exchange_rates_data_provider?
      assert_not family.missing_data_provider?
    end
  end

  test "local_date is the date in the family's zone" do
    family = families(:dylan_family)
    evening_utc = Time.utc(2026, 1, 15, 19, 0, 0)

    family.update!(timezone: "Australia/Sydney")
    assert_equal Date.new(2026, 1, 16), family.local_date(evening_utc)

    family.update!(timezone: "America/New_York")
    assert_equal Date.new(2026, 1, 15), family.local_date(Time.utc(2026, 1, 16, 3, 0, 0))
  end

  test "local_date falls back to the app's zone for a blank or unknown zone" do
    family = families(:dylan_family)
    evening_utc = Time.utc(2026, 1, 15, 19, 0, 0)

    family.update_column(:timezone, nil)
    assert_equal evening_utc.in_time_zone(Time.zone).to_date, family.local_date(evening_utc)

    family.update_column(:timezone, "Mars/Olympus_Mons")
    assert_equal evening_utc.in_time_zone(Time.zone).to_date, family.local_date(evening_utc)
  end

  test "investment_contributions_category creates category when missing" do
    family = families(:dylan_family)
    family.categories.where(name: Category.investment_contributions_name).destroy_all

    assert_nil family.categories.find_by(name: Category.investment_contributions_name)

    category = family.investment_contributions_category

    assert category.persisted?
    assert_equal Category.investment_contributions_name, category.name
    assert_equal "#0d9488", category.color
    assert_equal "trending-up", category.lucide_icon
  end

  test "investment_contributions_category returns existing category" do
    family = families(:dylan_family)
    existing = family.categories.find_or_create_by!(name: Category.investment_contributions_name) do |c|
      c.color = "#0d9488"
      c.lucide_icon = "trending-up"
    end

    assert_no_difference "Category.count" do
      result = family.investment_contributions_category
      assert_equal existing, result
    end
  end

  test "investment_contributions_category uses family locale consistently" do
    family = families(:dylan_family)
    family.update!(locale: "fr")
    family.categories.where(name: [ "Investment Contributions", "Contributions aux investissements" ]).destroy_all

    # Simulate different request locales (e.g., from Accept-Language header)
    # The category should always be created with the family's locale (French)
    category_from_english_request = I18n.with_locale(:en) do
      family.investment_contributions_category
    end

    assert_equal "Contributions aux investissements", category_from_english_request.name

    # Second request with different locale should find the same category
    assert_no_difference "Category.count" do
      category_from_dutch_request = I18n.with_locale(:nl) do
        family.investment_contributions_category
      end

      assert_equal category_from_english_request.id, category_from_dutch_request.id
      assert_equal "Contributions aux investissements", category_from_dutch_request.name
    end
  end

  test "investment_contributions_category prevents duplicate categories across locales" do
    family = families(:dylan_family)
    family.update!(locale: "en")
    family.categories.where(name: [ "Investment Contributions", "Contributions aux investissements" ]).destroy_all

    # Create category under English family locale
    english_category = family.investment_contributions_category
    assert_equal "Investment Contributions", english_category.name

    # Simulate a request with French locale (e.g., from browser Accept-Language)
    # Should still return the English category, not create a French one
    assert_no_difference "Category.count" do
      I18n.with_locale(:fr) do
        french_request_category = family.investment_contributions_category
        assert_equal english_category.id, french_request_category.id
        assert_equal "Investment Contributions", french_request_category.name
      end
    end
  end

  test "investment_contributions_category reuses legacy category with wrong locale" do
    family = families(:dylan_family)
    family.update!(locale: "fr")
    family.categories.where(name: [ "Investment Contributions", "Contributions aux investissements" ]).destroy_all

    # Simulate legacy: category was created with English name (old bug behavior)
    legacy_category = family.categories.create!(
      name: "Investment Contributions",
      color: "#0d9488",
      lucide_icon: "trending-up"
    )

    # Should find and reuse the legacy category, updating its name to French
    assert_no_difference "Category.count" do
      result = family.investment_contributions_category
      assert_equal legacy_category.id, result.id
      assert_equal "Contributions aux investissements", result.name
    end
  end

  test "investment_contributions_category merges multiple locale variants" do
    family = families(:dylan_family)
    family.update!(locale: "en")
    family.categories.where(name: [ "Investment Contributions", "Contributions aux investissements" ]).destroy_all

    # Simulate legacy: multiple categories created under different locales
    english_category = family.categories.create!(
      name: "Investment Contributions",
      color: "#0d9488",
      lucide_icon: "trending-up"
    )

    french_category = family.categories.create!(
      name: "Contributions aux investissements",
      color: "#0d9488",
      lucide_icon: "trending-up"
    )

    # Create transactions pointing to both categories
    account = family.accounts.first
    txn1 = Transaction.create!(category: english_category)
    Entry.create!(
      account: account,
      entryable: txn1,
      amount: 100,
      currency: "USD",
      date: Date.current,
      name: "Test 1"
    )

    txn2 = Transaction.create!(category: french_category)
    Entry.create!(
      account: account,
      entryable: txn2,
      amount: 200,
      currency: "USD",
      date: Date.current,
      name: "Test 2"
    )

    txn2_entry_updated_at = txn2.entry.updated_at

    # Should merge both categories into one, keeping the oldest
    assert_difference "Category.count", -1 do
      result = travel_to(1.minute.from_now) { family.investment_contributions_category }
      assert_equal english_category.id, result.id
      assert_equal "Investment Contributions", result.name

      # Both transactions should now point to the keeper
      assert_equal english_category.id, txn1.reload.category_id
      assert_equal english_category.id, txn2.reload.category_id

      # Reassignment must touch entries so entry-keyed caches bust
      # (only txn2 is reassigned — txn1 already points at the keeper)
      assert txn2.entry.reload.updated_at > txn2_entry_updated_at

      # French category should be deleted
      assert_nil Category.find_by(id: french_category.id)
    end
  end

  test "investment_contributions_category merges duplicates across accounts" do
    family = families(:dylan_family)
    family.update!(locale: "en")
    family.categories.where(name: [ "Investment Contributions", "Contributions aux investissements" ]).destroy_all

    english_category = family.categories.create!(
      name: "Investment Contributions",
      color: "#0d9488",
      lucide_icon: "trending-up"
    )

    french_category = family.categories.create!(
      name: "Contributions aux investissements",
      color: "#0d9488",
      lucide_icon: "trending-up"
    )

    # Transactions on two different accounts of the same family: the
    # transactions-through-accounts scope must reach both.
    txn1 = Transaction.create!(category: english_category)
    Entry.create!(
      account: accounts(:depository),
      entryable: txn1,
      amount: 100,
      currency: "USD",
      date: Date.current,
      name: "First account txn"
    )

    txn2 = Transaction.create!(category: french_category)
    Entry.create!(
      account: accounts(:credit_card),
      entryable: txn2,
      amount: 50,
      currency: "USD",
      date: Date.current,
      name: "Second account txn"
    )

    result = family.investment_contributions_category

    assert_equal english_category.id, result.id
    assert_equal english_category.id, txn1.reload.category_id
    assert_equal english_category.id, txn2.reload.category_id,
      "transaction on the second account must also be reassigned to the keeper"
  end

  test "moniker helpers return expected singular and plural labels" do
    family = families(:dylan_family)

    family.update!(moniker: "Family")
    assert_equal "Family", family.moniker_label
    assert_equal "Families", family.moniker_label_plural

    family.update!(moniker: "Group")
    assert_equal "Group", family.moniker_label
    assert_equal "Groups", family.moniker_label_plural
  end

  test "tags_version changes when tags are added, removed, merged or deleted" do
    family = families(:dylan_family)
    tag = family.tags.create!(name: "Version tag")
    other = family.tags.create!(name: "Other version tag")
    transaction = family.transactions.first

    assert_tags_version_changes(family) { transaction.toggle_tag!(tag) }
    assert_tags_version_changes(family) { transaction.toggle_tag!(tag) }
    assert_tags_version_changes(family) { transaction.toggle_tag!(other) }
    assert_tags_version_changes(family) { other.replace_and_destroy!(tag) }
    assert_tags_version_changes(family) { tag.destroy! }
  end

  test "holdings_version changes when a holding is edited or removed, and only then" do
    family = families(:dylan_family)
    holding = holdings(:one)

    assert_equal family.holdings_version, family.holdings_version, "stable while nothing changes"
    assert_holdings_version_changes(family) { holding.set_manual_cost_basis!(80) }
    assert_holdings_version_changes(family) { holding.unlock_cost_basis! }
    assert_holdings_version_changes(family) { holdings(:two).destroy! }
  end

  test "entries_cache_version changes when an older entry is destroyed" do
    family = families(:dylan_family)
    newer_entry = entries(:transaction)
    older_entry = Entry.create!(
      account: accounts(:depository),
      entryable: Transaction.create!(category: categories(:food_and_drink)),
      date: Date.current,
      name: "Older duplicate",
      amount: 42,
      currency: "USD",
      created_at: 2.days.ago,
      updated_at: 2.days.ago
    )

    newer_entry.update!(updated_at: 1.day.ago)

    before_destroy = family.reload.entries_cache_version
    older_entry.destroy!

    assert_not_equal before_destroy, family.reload.entries_cache_version
  end

  test "build_cache_key changes when family currency changes" do
    family = families(:empty)
    before = family.build_cache_key("test_key")
    family.update!(currency: "EUR")
    after = family.reload.build_cache_key("test_key")

    assert_not_equal before, after
  end

  test "build_cache_key changes through the account deletion lifecycle and does not revert" do
    family = families(:dylan_family)
    newer_account = accounts(:credit_card)
    older_account = accounts(:depository)

    newer_account.touch
    k0 = family.build_cache_key("test_key")

    older_account.mark_for_deletion!
    k1 = family.reload.build_cache_key("test_key")

    older_account.destroy!
    k2 = family.reload.build_cache_key("test_key")

    assert_not_equal k0, k1
    assert_not_equal k1, k2
    # Regression assertion for #4200: ensure key does not revert to pre-deletion state (k0)
    assert_not_equal k0, k2
  end

  test "build_cache_key remains unchanged when nothing relevant has changed" do
    family = families(:dylan_family)
    key1 = family.build_cache_key("test_key", invalidate_on_data_updates: true)
    key2 = family.reload.build_cache_key("test_key", invalidate_on_data_updates: true)

    assert_equal key1, key2
  end

  test "accounts_status_version fetches count and max updated_at in a single query" do
    family = families(:dylan_family)
    queries = capture_sql_queries do
      family.accounts_status_version
    end

    account_queries = queries.grep(/FROM "accounts"/i)
    assert_equal 1, account_queries.size, "accounts_status_version should execute only one query"
  end

  test "default currency comes from country ISO data" do
    assert_equal "CAD", Family.default_currency_for_country("CA")
    assert_equal "EUR", Family.default_currency_for_country("DE")
    assert_equal "BRL", Family.default_currency_for_country("BR")
    assert_equal "USD", Family.default_currency_for_country("unknown")
  end

  test "available_merchants includes family merchants without transactions" do
    family = families(:dylan_family)

    new_merchant = family.merchants.create!(name: "New Test Merchant")

    assert_includes family.available_merchants, new_merchant
  end

  test "known_merchant_names includes assigned and family-owned merchant names, deduplicates matching names, and excludes recently-unlinked merchants" do
    family = families(:dylan_family)

    provider_merchant = ProviderMerchant.create!(name: "Known Provider Merchant", source: "enable_banking")
    transactions(:one).update!(merchant: provider_merchant)

    # Same name as the assigned provider merchant, but a distinct record -- proves
    # the result is deduplicated by name value, not just by record identity.
    family.merchants.create!(name: "Known Provider Merchant")

    unassigned_family_merchant = family.merchants.create!(name: "Unassigned Family Merchant")

    # Assign then unlink a merchant -- available_merchants deliberately keeps
    # recently-unlinked merchants around (so the UI can offer a quick undo);
    # known_merchant_names must NOT, since it's used to auto-match/auto-assign new
    # transactions and re-surfacing a deliberately-removed association would undo
    # the user's action silently.
    unlinked_merchant = ProviderMerchant.create!(name: "Recently Unlinked Merchant", source: "enable_banking")
    transactions(:one).update!(merchant: unlinked_merchant)
    unlinked_merchant.unlink_from_family(family)
    transactions(:one).update!(merchant: provider_merchant)

    names = family.known_merchant_names

    assert_equal 1, names.count("Known Provider Merchant")
    assert_includes names, unassigned_family_merchant.name
    assert_not_includes names, "Recently Unlinked Merchant"
    assert_includes family.available_merchants.map(&:name), "Recently Unlinked Merchant"
  end

  test "enabled currencies always include the base currency" do
    family = families(:dylan_family)
    family.update!(currency: "SGD", enabled_currencies: [ "USD" ])

    family.update!(enabled_currencies: [ "USD" ])

    assert_equal [ "SGD", "USD" ], family.reload.enabled_currency_codes
  end

  test "currency is saved as its ISO code" do
    family = families(:dylan_family)
    family.update!(currency: "eur")

    assert_equal "EUR", family.reload.currency
  end

  test "an existing lowercase currency is saved as its ISO code" do
    family = families(:dylan_family)
    family.update_column(:currency, "eur")

    family.update!(name: "Renamed family")

    assert_equal "EUR", family.reload.currency
  end

  test "rejects a blank or unknown currency" do
    family = families(:dylan_family)

    [ "", nil, "XYZ" ].each do |value|
      assert_not family.update(currency: value)
      assert family.errors.of_kind?(:currency, :invalid)
    end
    assert_equal "USD", family.reload.currency
  end

  test "an existing unknown currency does not block unrelated updates" do
    family = families(:dylan_family)
    family.update_column(:currency, "XYZ")

    assert family.update(name: "Renamed family")
  end

  test "empty enabled currencies keeps all currencies available" do
    family = families(:dylan_family)
    family.update!(enabled_currencies: [])

    assert_nil family.reload.enabled_currencies
    assert_equal Money::Currency.as_options.map(&:iso_code), family.reload.enabled_currency_codes
  end

  test "enabled currencies are normalized and deduplicated" do
    family = families(:dylan_family)
    family.update!(currency: "SGD", enabled_currencies: [ "USD", "usd", "SGD" ])

    assert_equal [ "SGD", "USD" ], family.reload.enabled_currencies
    assert_equal [ "SGD", "USD" ], family.reload.enabled_currency_codes
  end

  test "all selected currencies collapse to default behavior" do
    family = families(:dylan_family)
    family.update!(enabled_currencies: Money::Currency.as_options.map(&:iso_code))

    assert_nil family.reload.enabled_currencies
    assert_equal Money::Currency.as_options.map(&:iso_code), family.reload.enabled_currency_codes
  end

  test "upload_document stores provided metadata and statement on family document" do
    family = families(:dylan_family)
    family.update!(vector_store_id: nil)

    adapter = mock("vector_store_adapter")
    adapter.expects(:create_store).with(name: "Family #{family.id} Documents").returns(
      VectorStore::Response.new(success?: true, data: { id: "vs_test123" }, error: nil)
    )
    adapter.expects(:upload_file).with(
      store_id: "vs_test123",
      file_content: "hello",
      filename: "notes.txt"
    ).returns(
      VectorStore::Response.new(success?: true, data: { file_id: "file-xyz" }, error: nil)
    )

    VectorStore::Registry.stubs(:adapter).returns(adapter)

    statement = AccountStatement.create_from_upload!(
      family: family, account: accounts(:connected),
      file: uploaded_file(filename: "statement.pdf", content_type: "application/pdf", content: "%PDF-1.4 statement")
    )

    document = family.upload_document(
      file_content: "hello",
      filename: "notes.txt",
      metadata: { "type" => "financial_document" },
      account_statement: statement
    )

    assert_not_nil document
    assert_equal({ "type" => "financial_document" }, document.metadata)
    assert_equal statement, document.reload.account_statement
    assert_equal "vs_test123", family.reload.vector_store_id
  end

  # auto_share_existing_accounts_with -----------------------------------------

  test "auto_share_existing_accounts_with shares existing family accounts read_write when sharing is default" do
    family = families(:dylan_family)
    family.update!(default_account_sharing: "shared")
    newcomer = users(:empty)
    newcomer.update_columns(family_id: family.id, role: "member")

    expected_ids = family.accounts.where.not(owner_id: newcomer.id).pluck(:id).sort
    assert expected_ids.any?, "fixture family must have shareable accounts"

    family.auto_share_existing_accounts_with(newcomer)

    shares = AccountShare.where(user: newcomer)
    assert_equal expected_ids, shares.pluck(:account_id).sort
    assert shares.all?(&:read_write?), "shares must grant read_write"
    assert shares.all?(&:include_in_finances?), "shares must be included in finances"
  end

  test "auto_share_existing_accounts_with shares existing family accounts read_only for guests" do
    family = families(:dylan_family)
    family.update!(default_account_sharing: "shared")
    newcomer = users(:empty)
    newcomer.update_columns(family_id: family.id, role: "guest")

    expected_ids = family.accounts.where.not(owner_id: newcomer.id).pluck(:id).sort
    assert expected_ids.any?, "fixture family must have shareable accounts"

    family.auto_share_existing_accounts_with(newcomer)

    shares = AccountShare.where(user: newcomer)
    assert_equal expected_ids, shares.pluck(:account_id).sort
    assert shares.all?(&:read_only?), "guest shares must grant read_only"
    assert shares.all?(&:include_in_finances?), "shares must be included in finances"
  end

  test "auto_share_existing_accounts_with is a no-op when family sharing is private" do
    family = families(:dylan_family)
    family.update!(default_account_sharing: "private")
    newcomer = users(:empty)
    newcomer.update_columns(family_id: family.id, role: "member")

    assert_no_difference "AccountShare.count" do
      family.auto_share_existing_accounts_with(newcomer)
    end
  end

  test "auto_share_existing_accounts_with does not share with a user outside the family" do
    family = families(:dylan_family)
    family.update!(default_account_sharing: "shared")
    outsider = users(:empty)
    outsider.update_columns(family_id: families(:empty).id, role: "member")

    assert_no_difference "AccountShare.count" do
      family.auto_share_existing_accounts_with(outsider)
    end
  end

  test "auto_share_existing_accounts_with never shares a user's own account and is idempotent" do
    family = families(:dylan_family)
    family.update!(default_account_sharing: "shared")
    newcomer = users(:empty)
    newcomer.update_columns(family_id: family.id, role: "member")
    owned = family.accounts.first
    owned.update!(owner: newcomer)

    family.auto_share_existing_accounts_with(newcomer)
    count_after_first = AccountShare.where(user: newcomer).count

    assert_not AccountShare.exists?(user: newcomer, account: owned),
      "must not share a user's own account with themselves"

    family.auto_share_existing_accounts_with(newcomer) # re-run

    assert_equal count_after_first, AccountShare.where(user: newcomer).count,
      "re-running must not create duplicate shares"
  end

  # Preview access is per-user, but jobs that act on family-scoped data have no
  # Current.user. One opted-in member enables the family.
  test "preview_features_enabled? is true when any member has opted in" do
    family = families(:dylan_family)
    family.users.each { |user| set_preview_features(user, false) }

    assert_not family.reload.preview_features_enabled?

    set_preview_features(family.users.first, true)

    assert family.reload.preview_features_enabled?
  end

  test "with_preview_features scope agrees with the predicate" do
    family = families(:dylan_family)
    family.users.each { |user| set_preview_features(user, false) }

    assert_not_includes Family.with_preview_features, family.reload

    set_preview_features(family.users.first, true)

    assert_includes Family.with_preview_features, family.reload
  end

  # The family rollup is a jsonb containment match; the UI gates on
  # User#preview_features_enabled?'s strict `== true`. If containment were the
  # looser of the two, the nightly job would generate for families whose UI
  # still hides the feature — so assert the user-level predicate agrees.
  test "with_preview_features ignores truthy non-boolean values" do
    family = families(:dylan_family)
    family.users.each { |user| set_preview_features(user, false) }
    set_preview_features(family.users.first, "yes")

    assert_not family.users.first.reload.preview_features_enabled?,
      "the per-user predicate the UI reads must reject a non-boolean"
    assert_not family.reload.preview_features_enabled?
    assert_not_includes Family.with_preview_features, family
  end

  test "rejects a timezone ActiveSupport::TimeZone doesn't recognize" do
    family = families(:dylan_family)
    family.timezone = "Invalid/Timezone"

    assert_not family.valid?
    assert_includes family.errors[:timezone], "is invalid"
  end

  test "accepts a timezone identifier, the form the settings dropdown actually submits" do
    family = families(:dylan_family)
    # LanguagesHelper#timezone_options submits tz.tzinfo.identifier (e.g.
    # "America/New_York"), not tz.name (e.g. "Eastern Time (US & Canada)") --
    # these differ for every zone Rails ships, so this is the case that
    # actually matters, not just the display name.
    family.timezone = "America/New_York"

    assert family.valid?
  end

  test "allows a blank timezone" do
    family = families(:dylan_family)
    family.timezone = nil

    assert family.valid?
  end

  test "stores an empty timezone from the settings form as nil" do
    family = families(:dylan_family)
    family.update!(timezone: "")

    assert_nil family.reload.timezone
  end

  test "stores a Rails zone name as its IANA identifier" do
    family = families(:dylan_family)
    family.update!(timezone: " Pacific Time (US & Canada) ")

    assert_equal "America/Los_Angeles", family.reload.timezone
  end

  test "does not re-validate an existing invalid timezone when saving unrelated changes" do
    family = families(:dylan_family)
    # Bypasses validations, simulating data that predates this validation --
    # e.g. the exact #390 scenario (a stale/renamed IANA zone already sitting
    # in the DB).
    family.update_column(:timezone, "Invalid/Timezone")

    family.name = "Updated name, timezone untouched"

    assert family.valid?, "an unrelated change must not be blocked by a pre-existing bad timezone"
    assert family.save
  end

  test "resolved_time_zone returns the family's zone" do
    family = families(:dylan_family)
    family.update_column(:timezone, "America/New_York")

    assert_equal "America/New_York", family.resolved_time_zone.name
  end

  test "resolved_time_zone falls back to the app default and logs once for a stale/invalid zone" do
    family = families(:dylan_family)
    family.update_column(:timezone, "Invalid/Timezone")

    original_cache = Rails.cache
    Rails.cache = ActiveSupport::Cache::MemoryStore.new

    assert_difference "DebugLogEntry.count", 1 do
      2.times { assert_equal Time.zone, family.resolved_time_zone }
    end

    entry = DebugLogEntry.order(:created_at).last
    assert_equal "warn", entry.level
    assert_includes entry.message, "Invalid/Timezone"
    assert_equal family, entry.family
  ensure
    Rails.cache = original_cache
  end

  test "resolved_time_zone falls back to the app default for a blank timezone" do
    family = families(:dylan_family)
    family.update_column(:timezone, nil)

    assert_equal Time.zone, family.resolved_time_zone
  end

  test "balance_sheet memoizes per user for the same family instance" do
    family = families(:dylan_family)
    admin = users(:family_admin)
    member = users(:family_member)

    first_call_for_admin = family.balance_sheet(user: admin)

    assert_same first_call_for_admin, family.balance_sheet(user: admin),
      "repeated calls for the same user must reuse the same BalanceSheet instance"

    refute_same first_call_for_admin, family.balance_sheet(user: member),
      "different users must not share a memoized BalanceSheet (family sharing scoping)"
  end

  test "investment_statement memoizes per user for the same family instance" do
    family = families(:dylan_family)
    admin = users(:family_admin)
    member = users(:family_member)

    first_call_for_admin = family.investment_statement(user: admin)

    assert_same first_call_for_admin, family.investment_statement(user: admin),
      "repeated calls for the same user must reuse the same InvestmentStatement instance"

    refute_same first_call_for_admin, family.investment_statement(user: member),
      "different users must not share a memoized InvestmentStatement (family sharing scoping)"
  end

  test "requests transaction refreshes for syncable Plaid items" do
    family = families(:dylan_family)

    assert_enqueued_with job: PlaidTransactionsRefreshAllJob, args: [ family, { source: "TestSync" } ] do
      family.request_plaid_transactions_refreshes_later(source: "TestSync")
    end
  end

  test "records a sanitized diagnostic and returns when Plaid refresh orchestration cannot be enqueued" do
    family = families(:dylan_family)

    PlaidTransactionsRefreshAllJob.stubs(:perform_later).raises(RedisClient::Error, "Redis unavailable")

    assert_difference "DebugLogEntry.count", 1 do
      assert_nil family.request_plaid_transactions_refreshes_later(source: "TestSync")
    end

    debug_entry = DebugLogEntry.order(:created_at).last
    assert_equal "TestSync", debug_entry.source
    assert_equal "RedisClient::Error", debug_entry.metadata["error_class"]
  end

  test "does not raise when both Plaid refresh enqueue and diagnostic capture fail" do
    family = families(:dylan_family)

    PlaidTransactionsRefreshAllJob.stubs(:perform_later).raises(RedisClient::Error, "Redis unavailable")
    DebugLogEntry.stubs(:capture).raises(ActiveRecord::ConnectionNotEstablished, "DB unavailable")

    assert_nil family.request_plaid_transactions_refreshes_later(source: "TestSync")
  end

  # A non-loopback http:// endpoint is the misconfiguration these guard: the
  # settings form rejects it, but JEV_ENDPOINT never passes through the form.
  # Marked for the secret scanner: a redaction test has to hold the shape it
  # redacts. The host and secrets are fake.
  CREDENTIALED_JEV_ENDPOINT = "http://someone:[email protected]/v1?api_key=QUERYSECRET#frag" # pipelock:ignore Credential in URL

  REJECTED_JEV_ENV = {
    "JEV_API_KEY" => "test_api_key",
    "JEV_ENDPOINT" => "http://internal-gateway.example.com/v1/systemone"
  }.freeze

  test "resolved_categorization_provider builds Jev when the endpoint is allowed" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "jev")

    with_env_overrides("JEV_API_KEY" => "test_api_key", "JEV_ENDPOINT" => "https://api.typesafe.ai/v1/systemone") do
      assert_instance_of Provider::Jev, family.resolved_categorization_provider
    end
  end

  test "the categorize plan names the Jev model when Jev will categorize" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "jev")

    with_env_overrides("JEV_API_KEY" => "test_api_key", "JEV_MODEL" => "~typesafe/jev-latest", "OPENAI_ACCESS_TOKEN" => "sk-test") do
      assert_equal "~typesafe/jev-latest", Ai.plan(:categorize, family:).model.name
      assert_equal family.resolved_categorization_provider.class, Provider::Jev
    end
  end

  test "the categorize plan names the Anthropic model when Anthropic will categorize" do
    family = families(:dylan_family)

    with_env_overrides("ANTHROPIC_API_KEY" => "test-key", "ANTHROPIC_MODEL" => "claude-sonnet-test", "LLM_PROVIDER" => "anthropic") do
      assert_equal "claude-sonnet-test", Ai.plan(:categorize, family:).model.name
    end
  end

  test "resolved_categorization_provider falls back to the LLM provider when the endpoint is rejected" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "jev")
    llm = Provider::Openai.allocate
    Provider::Registry.stubs(:preferred_llm_provider).returns(llm)

    with_env_overrides(REJECTED_JEV_ENV) do
      assert_same llm, family.resolved_categorization_provider
    end
  end

  test "resolved_categorization_provider does not write diagnostics from view-time callers" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "jev")
    Provider::Registry.stubs(:preferred_llm_provider).returns(nil)

    assert_no_difference "DebugLogEntry.count" do
      with_env_overrides(REJECTED_JEV_ENV) do
        assert_nil family.resolved_categorization_provider
      end
    end
  end

  test "the categorize plan leaves out a rejected Jev endpoint and writes no diagnostics" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "jev")

    assert_no_difference "DebugLogEntry.count" do
      with_env_overrides(REJECTED_JEV_ENV) do
        assert_nil Ai.plan(:categorize, family:)
      end
    end
  end

  test "shadow_categorization_provider returns nil when the Jev endpoint is rejected" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "llm")

    with_env_overrides(REJECTED_JEV_ENV) do
      assert_nil family.shadow_categorization_provider
    end
  end

  test "resolved_categorization_provider hands the construction error to a caller that asks" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "jev")
    Provider::Registry.stubs(:preferred_llm_provider).returns(nil)
    errors = []

    with_env_overrides(REJECTED_JEV_ENV) do
      assert_nil family.resolved_categorization_provider { |error| errors << error }
    end

    assert_equal [ Provider::Jev::Error ], errors.map(&:class)
  end

  # The rescue is deliberately narrow, so a registry bug still surfaces rather
  # than being reported to the operator as a Jev misconfiguration.
  test "resolved_categorization_provider does not swallow non-provider errors" do
    family = families(:dylan_family)
    family.update!(categorization_provider: "jev")
    Provider::Registry.stubs(:get_provider).with(:jev).raises(ArgumentError, "boom")

    assert_raises(ArgumentError) { family.resolved_categorization_provider }
  end

  # The currencies whose amounts every converted total leaves out (#3640).
  test "currencies_without_exchange_rate names used currencies with no rate on any date" do
    family = families(:empty)
    family.accounts.create!(name: "JPY", balance: 1, currency: "JPY", accountable: Depository.new)
    family.accounts.create!(name: "KRW", balance: 1, currency: "KRW", accountable: Depository.new)
    family.accounts.create!(name: "Home", balance: 1, currency: family.currency, accountable: Depository.new)
    ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 400.days.ago.to_date, rate: 0.009)

    assert_equal %w[KRW], family.currencies_without_exchange_rate
  end

  test "stale_exchange_rate_dates names used currencies whose newest rate is out of date" do
    family = families(:empty)
    family.accounts.create!(name: "JPY", balance: 1, currency: "JPY", accountable: Depository.new)
    family.accounts.create!(name: "CAD", balance: 1, currency: "CAD", accountable: Depository.new)
    ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 30.days.ago.to_date, rate: 0.0067)
    ExchangeRate.create!(from_currency: "CAD", to_currency: family.currency, date: Date.current, rate: 0.73)

    assert_equal({ "JPY" => 30.days.ago.to_date }, family.stale_exchange_rate_dates)
  end

  # The stale note says today's totals use the old rate, so it names only
  # currencies today's totals convert: account balances and current holdings.
  # A trip's yen spending from long ago still has an old newest rate, but
  # nothing converts it today.
  test "stale_exchange_rate_dates ignores a currency only old entries use" do
    family = families(:empty)
    home = family.accounts.create!(name: "Home", balance: 1, currency: family.currency, accountable: Depository.new)
    home.entries.create!(name: "Tokyo dinner", date: 400.days.ago.to_date, amount: 5_000, currency: "JPY",
                         entryable: Transaction.new)
    ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 400.days.ago.to_date, rate: 0.0067)

    assert_empty family.stale_exchange_rate_dates
  end

  test "stale_exchange_rate_dates names the currency of a current holding" do
    family = families(:empty)
    account = family.accounts.create!(name: "Brokerage", balance: 1, currency: family.currency, accountable: Investment.new)
    security = Security.create!(ticker: "JPH#{SecureRandom.hex(2)}", name: "Tokyo Listed")
    account.holdings.create!(security: security, date: Date.current, qty: 1, price: 1_000, amount: 1_000, currency: "JPY")
    ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 30.days.ago.to_date, rate: 0.0067)

    assert_equal({ "JPY" => 30.days.ago.to_date }, family.stale_exchange_rate_dates)
  end

  # A trade can be priced in a currency neither its entry nor its account
  # uses, and holding cost converts that currency.
  test "currencies_without_exchange_rate includes currencies only a trade uses" do
    family = families(:empty)
    account = family.accounts.create!(name: "Brokerage", balance: 1, currency: family.currency, accountable: Investment.new)
    security = Security.create!(ticker: "SEK#{SecureRandom.hex(2)}", name: "Stockholm Listed")
    account.entries.create!(name: "Buy", date: Date.current, amount: 100, currency: family.currency,
                            entryable: Trade.new(security: security, qty: 1, price: 1000, currency: "SEK"))

    assert_equal %w[SEK], family.currencies_without_exchange_rate
  end

  test "a disabled account's currency is not named" do
    family = families(:empty)
    family.accounts.create!(name: "Old KRW", balance: 1, currency: "KRW", accountable: Depository.new, status: "disabled")

    assert_empty family.currencies_without_exchange_rate
  end

  # The pages pass the viewer's accounts, so a member is not told about an
  # account they cannot see, and the note matches the totals they get.
  test "currencies_without_exchange_rate names only the given accounts' currencies" do
    family = families(:empty)
    home = family.accounts.create!(name: "Home", balance: 1, currency: family.currency, accountable: Depository.new)
    family.accounts.create!(name: "KRW", balance: 1, currency: "KRW", accountable: Depository.new)

    assert_equal %w[KRW], family.currencies_without_exchange_rate
    assert_empty family.currencies_without_exchange_rate(accounts: family.accounts.where(id: home.id))
  end

  test "earliest_activity_date ignores valuations, using earliest Transaction/Trade entry" do
    family = families(:empty)
    account = family.accounts.create!(name: "Checking", balance: 0, currency: "USD", accountable: Depository.new)

    account.entries.create!(date: Date.new(2000, 1, 15), name: "Old valuation",
                            amount: 5000, currency: "USD", entryable: Valuation.new)
    transaction_date = Date.new(2025, 3, 10)
    account.entries.create!(date: transaction_date, name: "Groceries",
                            amount: -50, currency: "USD", entryable: Transaction.new)

    assert_equal transaction_date, family.earliest_activity_date

    # A Trade earlier than the Transaction must win, so a regression that
    # drops Trade from the filter is caught (#4007).
    trade_date = Date.new(2020, 6, 15)
    account.entries.create!(date: trade_date, name: "Investment purchase",
                            amount: 100, currency: "USD",
                            entryable: Trade.new(security: securities(:aapl), qty: 1, price: 100, currency: "USD"))

    assert_equal trade_date, family.earliest_activity_date
  end

  test "earliest_activity_date returns nil when family has no Transaction/Trade entries" do
    family = families(:empty)
    account = family.accounts.create!(name: "House", balance: 0, currency: "USD", accountable: Depository.new)
    account.entries.create!(date: Date.new(2000, 1, 15), name: "Old valuation",
                            amount: 5000, currency: "USD", entryable: Valuation.new)

    assert_nil family.earliest_activity_date
  end

  private
    def assert_tags_version_changes(family)
      before = family.tags_version
      yield
      assert_not_equal before, family.reload.tags_version
    end

    def assert_holdings_version_changes(family)
      before = family.holdings_version
      yield
      assert_not_equal before, family.holdings_version
    end

    def set_preview_features(user, enabled)
      user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => enabled))
    end
end