Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
141 KB
Raw Blame
require "test_helper"

class Family::DataImporterTest < ActiveSupport::TestCase
  include EntriesTestHelper

  setup do
    @family = families(:empty)
  end

  test "imports accounts with accountable data" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-account-1",
          name: "Test Checking",
          balance: "1500.00",
          currency: "USD",
          accountable_type: "Depository",
          accountable: { subtype: "checking" }
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    assert_equal 1, result[:account_ids].count
    account = Account.find(result[:account_ids].first)
    assert_equal "Test Checking", account.name
    assert_equal 1500.0, account.balance.to_f
    assert_equal "USD", account.currency
    assert_equal "Depository", account.accountable_type
  end

  test "round trips loan terms through full export" do
    source_family = Family.create!(name: "Source Loan Family", currency: "EUR", locale: "en", date_format: "%Y-%m-%d")
    source_family.accounts.create!(
      name: "Round Trip Land Loan",
      balance: 18_000,
      currency: "USD",
      accountable: Loan.new(
        subtype: "other",
        interest_rate: 7.25,
        rate_type: "variable",
        term_months: 120,
        start_date: Date.new(2025, 3, 1),
        down_payment: 4_000,
        initial_balance: 20_000,
        insurance_rate: 0.35,
        insurance_rate_type: "level_term",
        day_count_convention: "actual_365",
        principal_only_transfers: true,
        variable_rate_schedule: { "2026-01-01" => "6.5" }
      )
    )

    Family::DataImporter.new(@family, full_export_ndjson(source_family)).import!

    loan = @family.accounts.find_by!(name: "Round Trip Land Loan").accountable
    assert_equal "other", loan.subtype
    assert_equal BigDecimal("7.25"), loan.interest_rate
    assert_equal "variable", loan.rate_type
    assert_equal 120, loan.term_months
    assert_equal Date.new(2025, 3, 1), loan.start_date
    assert_equal BigDecimal("4000"), loan.down_payment
    assert_equal BigDecimal("20000"), loan.initial_balance
    assert_equal BigDecimal("0.35"), loan.insurance_rate
    assert_equal "level_term", loan.insurance_rate_type
    assert_equal "actual_365", loan.day_count_convention
    assert loan.principal_only_transfers
    assert_equal [ [ Date.new(2026, 1, 1), BigDecimal("6.5") ] ], loan.variable_rates
  end

  test "round trips credit card details through full export" do
    source_family = Family.create!(name: "Source Card Family", currency: "EUR", locale: "en", date_format: "%Y-%m-%d")
    source_family.accounts.create!(
      name: "Round Trip Card",
      balance: 350,
      currency: "EUR",
      accountable: CreditCard.new(
        subtype: "credit_card",
        apr: 19.9,
        annual_fee: 45,
        minimum_payment: 25,
        available_credit: 2_650,
        due_day: 5,
        statement_close_day: 20,
        expiration_date: Date.new(2029, 8, 31)
      )
    )

    Family::DataImporter.new(@family, full_export_ndjson(source_family)).import!

    card = @family.accounts.find_by!(name: "Round Trip Card").accountable
    assert_equal BigDecimal("19.9"), card.apr
    assert_equal BigDecimal("45"), card.annual_fee
    assert_equal BigDecimal("25"), card.minimum_payment
    assert_equal BigDecimal("2650"), card.available_credit
    assert_equal 5, card.due_day
    assert_equal 20, card.statement_close_day
    assert_equal Date.new(2029, 8, 31), card.expiration_date
  end

  test "round trips vehicle details through full export" do
    source_family = Family.create!(name: "Source Vehicle Family", currency: "EUR", locale: "en", date_format: "%Y-%m-%d")
    source_family.accounts.create!(
      name: "Round Trip Car",
      balance: 18_500,
      currency: "EUR",
      accountable: Vehicle.new(subtype: "car", make: "Toyota", model: "Camry", year: 2024, mileage_value: 15_000, mileage_unit: "km")
    )

    Family::DataImporter.new(@family, full_export_ndjson(source_family)).import!

    vehicle = @family.accounts.find_by!(name: "Round Trip Car").accountable
    assert_equal "car", vehicle.subtype
    assert_equal "Toyota", vehicle.make
    assert_equal "Camry", vehicle.model
    assert_equal 2024, vehicle.year
    assert_equal 15_000, vehicle.mileage_value
    assert_equal "km", vehicle.mileage_unit
  end

  test "imports vehicles from an export without their details or with null details" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "old-car", name: "Old Car", balance: "5000", currency: "USD", accountable_type: "Vehicle", accountable: { subtype: "car" } } },
      { type: "Account", data: { id: "null-car", name: "Null Car", balance: "5000", currency: "USD", accountable_type: "Vehicle",
                                 accountable: { subtype: "car", make: nil, model: nil, year: nil, mileage_value: nil, mileage_unit: nil } } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    [ "Old Car", "Null Car" ].each do |name|
      vehicle = @family.accounts.find_by!(name: name).accountable
      assert_nil vehicle.make
      assert_nil vehicle.year
      assert_nil vehicle.mileage_value
      assert_equal "mi", vehicle.mileage_unit
    end
  end

  test "imports loans and credit cards from an export without their details" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "old-loan", name: "Old Loan", balance: "1000", currency: "USD", subtype: "auto", accountable_type: "Loan", accountable: { subtype: "auto" } } },
      { type: "Account", data: { id: "old-card", name: "Old Card", balance: "100", currency: "USD", accountable_type: "CreditCard", accountable: { subtype: "credit_card" } } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    loan = @family.accounts.find_by!(name: "Old Loan").accountable
    assert_equal "auto", loan.subtype
    assert_nil loan.interest_rate
    assert_equal Loan::DEFAULT_DAY_COUNT_CONVENTION, loan.day_count_convention
    assert_not loan.principal_only_transfers
    assert_equal({}, loan.variable_rate_schedule)

    card = @family.accounts.find_by!(name: "Old Card").accountable
    assert_nil card.apr
    assert_nil card.due_day
  end

  test "keeps the nested accountable subtype when the account has no top-level subtype" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "a1", name: "Nested", balance: "0", currency: "USD", accountable_type: "Depository", accountable: { subtype: "savings" } } },
      { type: "Account", data: { id: "a2", name: "Both", balance: "0", currency: "USD", accountable_type: "Depository", subtype: "savings", accountable: { subtype: "checking" } } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    assert_equal "savings", @family.accounts.find_by!(name: "Nested").accountable.subtype
    assert_equal "checking", @family.accounts.find_by!(name: "Both").accountable.subtype
  end

  test "does not store a blank nested accountable subtype" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "a1", name: "Blank Nested", balance: "0", currency: "USD", accountable_type: "Depository", accountable: { subtype: "" } } },
      { type: "Account", data: { id: "a2", name: "Blank Nested With Top Level", balance: "0", currency: "USD", subtype: "savings", accountable_type: "Depository", accountable: { subtype: "" } } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    assert_nil @family.accounts.find_by!(name: "Blank Nested").accountable.subtype
    assert_equal "savings", @family.accounts.find_by!(name: "Blank Nested With Top Level").accountable.subtype
  end

  test "imports a loan whose detail columns are null in the export" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-loan", name: "Null Loan", balance: "1000", currency: "USD", accountable_type: "Loan",
          accountable: { interest_rate: "5.0", day_count_convention: nil, principal_only_transfers: nil, variable_rate_schedule: nil, start_date: nil }
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    loan = @family.accounts.find_by!(name: "Null Loan").accountable
    assert_equal BigDecimal("5"), loan.interest_rate
    assert_equal Loan::DEFAULT_DAY_COUNT_CONVENTION, loan.day_count_convention
    assert_not loan.principal_only_transfers
    assert_equal({}, loan.variable_rate_schedule)
  end

  test "rejects a loan rate schedule that cannot be read" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-loan", name: "Bad Schedule Loan", balance: "1000", currency: "USD", accountable_type: "Loan",
          accountable: { rate_type: "variable", interest_rate: "5", variable_rate_schedule: { "not a date" => "6" } }
        }
      }
    ])

    assert_raises(ActiveRecord::RecordInvalid) { Family::DataImporter.new(@family, ndjson).import! }
    assert_not @family.accounts.exists?(name: "Bad Schedule Loan")
  end

  test "imports into existing accounts given as account targets" do
    account = @family.accounts.create!(name: "Existing", balance: 0, currency: "USD", accountable: Depository.new)
    ndjson = build_ndjson([
      { type: "Transaction", data: { id: "old-txn", account_id: "old-account", date: "2024-01-02", amount: "10.00", name: "Grocer" } }
    ])

    result = Family::DataImporter.new(@family, ndjson, account_targets: { "old-account" => account }).import!

    assert_empty result[:account_ids]
    assert_equal [ "Grocer" ], account.entries.pluck(:name)
  end

  test "keeps a transaction's own extra metadata and import lock" do
    account = @family.accounts.create!(name: "Existing", balance: 0, currency: "USD", accountable: Depository.new)
    ndjson = build_ndjson([
      { type: "Transaction", data: { id: "old-txn", account_id: "old-account", date: "2024-01-02", amount: "10.00",
        name: "Grocer", extra: { monarch: { transaction_id: "1" } }, import_locked: true } }
    ])

    Family::DataImporter.new(@family, ndjson, account_targets: { "old-account" => account }).import!

    entry = account.entries.sole
    assert_equal({ "monarch" => { "transaction_id" => "1" } }, entry.transaction.extra)
    assert entry.import_locked?
    assert_nil entry.external_id
  end

  test "restores the Brandfetch logo choice so no fetched icon replaces it" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-account-1",
          name: "Test Checking",
          balance: "1500.00",
          currency: "USD",
          institution_domain: "tbank.ru",
          logo_selection: "brandfetch",
          accountable_type: "Depository",
          accountable: { subtype: "checking" }
        }
      }
    ])

    account_id = Family::DataImporter.new(@family, ndjson).import![:account_ids].first
    account = Account.find(account_id)

    assert account.reload.logo_brandfetch?
    assert_not account.logo_auto_fetchable?
  end

  test "an unknown logo selection imports as the automatic one" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-account-1",
          name: "Test Checking",
          balance: "1500.00",
          currency: "USD",
          logo_selection: "some-future-source",
          accountable_type: "Depository",
          accountable: { subtype: "checking" }
        }
      }
    ])

    account_id = Family::DataImporter.new(@family, ndjson).import![:account_ids].first
    account = Account.find(account_id)

    assert account.reload.logo_automatic?
  end

  test "restores an account's cost basis method" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-account-1",
          name: "Brokerage",
          balance: "1500.00",
          currency: "USD",
          cost_basis_method: "fifo",
          accountable_type: "Investment",
          accountable: {}
        }
      }
    ])

    account_id = Family::DataImporter.new(@family, ndjson).import![:account_ids].first

    assert Account.find(account_id).cost_basis_fifo?
  end

  test "an export without a known cost basis method imports as average" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: { id: "old-account-1", name: "Older", balance: "100", currency: "USD", accountable_type: "Investment", accountable: {} }
      },
      {
        type: "Account",
        data: { id: "old-account-2", name: "Newer", balance: "100", currency: "USD", cost_basis_method: "some-future-method", accountable_type: "Investment", accountable: {} }
      }
    ])

    account_ids = Family::DataImporter.new(@family, ndjson).import![:account_ids]

    assert_equal %w[average average], Account.where(id: account_ids).pluck(:cost_basis_method)
  end

  test "imports non-destructive account status from ndjson" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "disabled-account",
          name: "Closed Checking",
          balance: "0.00",
          currency: "USD",
          accountable_type: "Depository",
          status: "disabled"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    account = Account.find(result[:account_ids].first)
    assert_equal "Closed Checking", account.name
    assert_equal "disabled", account.status
  end

  test "does not import pending deletion account status" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "pending-delete-account",
          name: "Pending Delete Checking",
          balance: "0.00",
          currency: "USD",
          accountable_type: "Depository",
          status: "pending_deletion"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    account = Account.find(result[:account_ids].first)
    assert_equal "Pending Delete Checking", account.name
    assert_equal "active", account.status
  end

  test "imports raw balance history records" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Balance History Checking",
          balance: "1200.00",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Balance",
        data: {
          id: "balance-1",
          account_id: "acct-1",
          date: "2024-01-31",
          balance: "1200.00",
          currency: "USD",
          cash_balance: "1100.00",
          start_cash_balance: "1000.00",
          start_non_cash_balance: "0.00",
          cash_inflows: "300.00",
          cash_outflows: "200.00",
          non_cash_inflows: "0.00",
          non_cash_outflows: "0.00",
          net_market_flows: "0.00",
          cash_adjustments: "0.00",
          non_cash_adjustments: "0.00",
          flows_factor: 1
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Balance History Checking")
    balance = account.balances.find_by!(date: Date.parse("2024-01-31"), currency: "USD")

    assert_equal 1200.0, balance.balance.to_f
    assert_equal 1100.0, balance.cash_balance.to_f
    assert_equal 1000.0, balance.start_cash_balance.to_f
    assert_equal 300.0, balance.cash_inflows.to_f
    assert_equal 200.0, balance.cash_outflows.to_f
    assert_equal 1, balance.flows_factor
  end

  test "counts skipped balance rows with blank account references once" do
    ndjson = build_ndjson([
      {
        type: "Balance",
        data: {
          id: "balance-1",
          account_id: "",
          date: "2024-01-31",
          balance: "1200.00",
          currency: "USD"
        }
      }
    ])

    result = Family::DataImporter.new(@family, ndjson).import!

    assert_equal 1, result.dig(:summary, "balances", "skipped")
    assert_not Balance.exists?(date: Date.iso8601("2024-01-31"), currency: "USD", balance: BigDecimal("1200.00"))
  end

  test "imports duplicate raw balance records idempotently by account date and currency" do
    balance_record = {
      type: "Balance",
      data: {
        id: "balance-1",
        account_id: "acct-1",
        date: "2024-01-31",
        balance: "1200.00",
        currency: "USD",
        cash_balance: "1100.00",
        flows_factor: 1
      }
    }

    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Idempotent Balance Checking",
          balance: "1200.00",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      balance_record,
      balance_record.deep_merge(data: { id: "balance-1-duplicate", balance: "1300.00", cash_balance: "1250.00" })
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Idempotent Balance Checking")
    assert_equal 1, account.balances.where(date: Date.parse("2024-01-31"), currency: "USD").count

    balance = account.balances.find_by!(date: Date.parse("2024-01-31"), currency: "USD")
    assert_equal 1300.0, balance.balance.to_f
    assert_equal 1250.0, balance.cash_balance.to_f
  end

  test "preserves omitted raw balance components on duplicate records" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Partial Balance Checking",
          balance: "1200.00",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Balance",
        data: {
          id: "balance-1",
          account_id: "acct-1",
          date: "2024-01-31",
          balance: "1200.00",
          currency: "USD",
          cash_balance: "1100.00",
          cash_inflows: "300.00",
          cash_outflows: "200.00",
          flows_factor: -1
        }
      },
      {
        type: "Balance",
        data: {
          id: "balance-1-partial",
          account_id: "acct-1",
          date: "2024-01-31",
          balance: "1300.00",
          currency: "USD"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Partial Balance Checking")
    balance = account.balances.find_by!(date: Date.parse("2024-01-31"), currency: "USD")

    assert_equal 1300.0, balance.balance.to_f
    assert_equal 1100.0, balance.cash_balance.to_f
    assert_equal 300.0, balance.cash_inflows.to_f
    assert_equal 200.0, balance.cash_outflows.to_f
    assert_equal(-1, balance.flows_factor)
  end

  test "dates synthesized account opening balance before imported balance history" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Balance Anchored Checking",
          balance: "500.00",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Balance",
        data: {
          id: "balance-1",
          account_id: "acct-1",
          date: "2024-02-01",
          balance: "500.00",
          currency: "USD"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Balance Anchored Checking")
    opening_anchor = account.valuations.opening_anchor.first

    assert_not_nil opening_anchor
    assert_equal Date.parse("2024-01-31"), opening_anchor.entry.date
  end

  test "dates synthesized account opening balance before oldest imported activity" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Main Account",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "txn-1",
          account_id: "acct-1",
          date: "2020-04-02",
          amount: "-50.00",
          name: "Grocery Store",
          currency: "USD"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Main Account")
    opening_anchor = account.valuations.opening_anchor.first

    assert_not_nil opening_anchor
    assert_equal Date.parse("2020-04-01"), opening_anchor.entry.date
  end

  test "clamps explicit account opening balance dates before imported activity" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Main Account",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository",
          opening_balance_date: "2020-04-02"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "txn-1",
          account_id: "acct-1",
          date: "2020-04-02",
          amount: "-50.00",
          name: "Grocery Store",
          currency: "USD"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Main Account")
    opening_anchor = account.valuations.opening_anchor.first

    assert_not_nil opening_anchor
    assert_equal Date.parse("2020-04-01"), opening_anchor.entry.date
  end

  test "imports explicit opening anchor valuations without synthesizing duplicates" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Main Account",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Valuation",
        data: {
          id: "val-opening",
          account_id: "acct-1",
          date: "2020-04-01",
          amount: "5000",
          name: "Opening balance",
          currency: "USD",
          kind: "opening_anchor"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Main Account")
    opening_anchors = account.valuations.opening_anchor.to_a

    assert_equal 1, opening_anchors.count
    assert_equal Date.parse("2020-04-01"), opening_anchors.first.entry.date
    assert_equal 5000.0, opening_anchors.first.entry.amount.to_f
  end

  test "skips synthesized opening anchor for authoritative balance history imports" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Imported With Full History",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository",
          authoritative_balance_history: true
        }
      },
      {
        type: "Valuation",
        data: {
          id: "val-1",
          account_id: "acct-1",
          date: "2020-04-01",
          amount: "4900",
          name: "Imported balance",
          currency: "USD",
          kind: "reconciliation"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Imported With Full History")

    assert_equal 5000.0, account.balance.to_f
    assert_empty account.valuations.opening_anchor
    assert_equal 1, account.valuations.reconciliation.count
  end

  test "imports categories with parent relationships" do
    ndjson = build_ndjson([
      {
        type: "Category",
        data: {
          id: "cat-parent",
          name: "Shopping",
          color: "#FF5733",
          classification: "expense"
        }
      },
      {
        type: "Category",
        data: {
          id: "cat-child",
          name: "Groceries",
          color: "#33FF57",
          classification: "expense",
          parent_id: "cat-parent"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    parent = @family.categories.find_by(name: "Shopping")
    child = @family.categories.find_by(name: "Groceries")

    assert_not_nil parent
    assert_not_nil child
    assert_equal parent.id, child.parent_id
  end

  test "imports tags" do
    ndjson = build_ndjson([
      {
        type: "Tag",
        data: {
          id: "tag-1",
          name: "Important",
          color: "#FF0000"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    tag = @family.tags.find_by(name: "Important")
    assert_not_nil tag
    assert_equal "#FF0000", tag.color
  end

  test "imports tags with deterministic fallback color when source omits color" do
    ndjson = build_ndjson([
      {
        type: "Tag",
        data: {
          id: "tag-1",
          name: "Important"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    tag = @family.tags.find_by!(name: "Important")
    assert_equal Tag::COLORS.first, tag.color
  end

  test "round trips a property's cost tag through full export" do
    source_family = Family.create!(name: "Source Cost Tag Family", currency: "USD", locale: "en", date_format: "%Y-%m-%d")
    tag = source_family.tags.create!(name: "Round Trip Land Costs")
    source_family.accounts.create!(name: "Round Trip Plot", balance: 30_000, currency: "USD", accountable: Property.new(cost_tag: tag))

    ndjson = nil
    Zip::File.open_buffer(Family::DataExporter.new(source_family).generate_export) do |zip|
      ndjson = zip.read("all.ndjson")
    end

    Family::DataImporter.new(@family, ndjson).import!

    imported_tag = @family.tags.find_by!(name: "Round Trip Land Costs")
    assert_not_equal tag.id, imported_tag.id
    assert_equal imported_tag.id, @family.accounts.find_by!(name: "Round Trip Plot").property.cost_tag_id
  end

  test "a property whose cost tag is not in the import is left unlinked" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "old-plot", name: "Orphan Plot", balance: "100", currency: "USD",
                                 accountable_type: "Property", accountable: { cost_tag_id: "missing-tag" } } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    assert_nil @family.accounts.find_by!(name: "Orphan Plot").property.cost_tag_id
  end

  test "a session mapping to a since-deleted cost tag leaves the property unlinked" do
    session = @family.import_sessions.create!(expected_chunks: 1)
    tag = @family.tags.create!(name: "Gone Land Costs")
    session.source_mappings.create!(family: @family, source_type: "Tag", source_id: "tag-gone", target: tag)
    tag.delete

    ndjson = build_ndjson([
      { type: "Account", data: { id: "old-plot", name: "Replayed Plot", balance: "100", currency: "USD",
                                 accountable_type: "Property", accountable: { cost_tag_id: "tag-gone" } } }
    ])

    Family::DataImporter.new(@family, ndjson, import_session: session).import!

    assert_nil @family.accounts.find_by!(name: "Replayed Plot").property.cost_tag_id
  end

  test "a replayed import clears a cost tag link the file no longer has" do
    session = @family.import_sessions.create!(expected_chunks: 1)
    tag = @family.tags.create!(name: "Replayed Land Costs")
    session.source_mappings.create!(family: @family, source_type: "Tag", source_id: "tag-1", target: tag)
    plot = { type: "Account", data: { id: "old-plot", name: "Relinked Plot", balance: "100", currency: "USD",
                                      accountable_type: "Property", accountable: { cost_tag_id: "tag-1" } } }

    Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!
    property = @family.accounts.find_by!(name: "Relinked Plot").property
    assert_equal tag.id, property.cost_tag_id

    plot[:data][:accountable] = { cost_tag_id: "tag-unknown" }
    Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!
    assert_nil property.reload.cost_tag_id

    plot[:data][:accountable] = { cost_tag_id: "tag-1" }
    Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!
    assert_equal tag.id, property.reload.cost_tag_id

    plot[:data][:accountable] = { cost_tag_id: nil }
    Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!
    assert_nil property.reload.cost_tag_id
  end

  test "an import without the cost tag key keeps the property's link" do
    session = @family.import_sessions.create!(expected_chunks: 1)
    tag = @family.tags.create!(name: "Kept Land Costs")
    session.source_mappings.create!(family: @family, source_type: "Tag", source_id: "tag-1", target: tag)
    plot = { type: "Account", data: { id: "old-plot", name: "Kept Plot", balance: "100", currency: "USD",
                                      accountable_type: "Property", accountable: { cost_tag_id: "tag-1" } } }
    Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!

    plot[:data][:accountable] = {}
    Family::DataImporter.new(@family, build_ndjson([ plot ]), import_session: session).import!

    assert_equal tag.id, @family.accounts.find_by!(name: "Kept Plot").property.cost_tag_id
  end

  test "imports merchants" do
    ndjson = build_ndjson([
      {
        type: "Merchant",
        data: {
          id: "merchant-1",
          name: "Amazon"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    merchant = @family.merchants.find_by(name: "Amazon")
    assert_not_nil merchant
  end

  test "imports recurring transactions with remapped account and merchant references" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Main Checking",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Merchant",
        data: {
          id: "merchant-1",
          name: "Internet Provider"
        }
      },
      {
        type: "RecurringTransaction",
        data: {
          id: "recurring-1",
          account_id: "acct-1",
          merchant_id: "merchant-1",
          amount: "-89.99",
          currency: "USD",
          expected_day_of_month: 14,
          last_occurrence_date: "2024-01-14",
          next_expected_date: "2024-02-14",
          status: "active",
          occurrence_count: 6,
          manual: true,
          payment_url: "https://pay.example.com/internet",
          expected_amount_min: "-95.00",
          expected_amount_max: "-85.00",
          expected_amount_avg: "-89.99"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    recurring_transaction = @family.recurring_transactions.first
    assert_not_nil recurring_transaction
    assert_equal "Main Checking", recurring_transaction.account.name
    assert_equal "Internet Provider", recurring_transaction.merchant.name
    assert_equal(-89.99, recurring_transaction.amount.to_f)
    assert_equal "USD", recurring_transaction.currency
    assert_equal 14, recurring_transaction.expected_day_of_month
    assert_equal Date.parse("2024-01-14"), recurring_transaction.last_occurrence_date
    assert_equal Date.parse("2024-02-14"), recurring_transaction.next_expected_date
    assert_equal "active", recurring_transaction.status
    assert_equal 6, recurring_transaction.occurrence_count
    assert_equal true, recurring_transaction.manual
    assert_equal "https://pay.example.com/internet", recurring_transaction.payment_url
    assert_equal(-95.0, recurring_transaction.expected_amount_min.to_f)
    assert_equal(-85.0, recurring_transaction.expected_amount_max.to_f)
    assert_equal(-89.99, recurring_transaction.expected_amount_avg.to_f)
  end

  test "round trips recurring transaction export semantics" do
    source_family = Family.create!(name: "Recurring Source", currency: "USD")
    source_account = source_family.accounts.create!(
      name: "Source Checking",
      accountable: Depository.new,
      balance: 1000,
      currency: "USD"
    )
    source_merchant = source_family.merchants.create!(name: "Internet Provider")

    source_family.recurring_transactions.create!(
      account: source_account,
      merchant: source_merchant,
      amount: -89.99,
      currency: "USD",
      expected_day_of_month: 14,
      last_occurrence_date: Date.parse("2024-01-14"),
      next_expected_date: Date.parse("2024-02-14"),
      status: "active",
      occurrence_count: 6,
      manual: true,
      expected_amount_min: -95,
      expected_amount_max: -85,
      expected_amount_avg: -89.99
    )

    source_family.recurring_transactions.create!(
      name: "Quarterly Insurance",
      amount: 240,
      currency: "USD",
      expected_day_of_month: 28,
      last_occurrence_date: Date.parse("2024-01-28"),
      next_expected_date: Date.parse("2024-04-28"),
      status: "inactive",
      occurrence_count: 2,
      manual: false
    )

    ndjson = nil
    Zip::File.open_buffer(Family::DataExporter.new(source_family).generate_export) do |zip|
      ndjson = zip.read("all.ndjson")
    end

    assert_not_nil ndjson
    assert ndjson.include?('"type":"RecurringTransaction"')

    Family::DataImporter.new(@family, ndjson).import!

    assert_equal 2, @family.recurring_transactions.count

    restored_account = @family.accounts.find_by!(name: "Source Checking")
    restored_merchant = @family.merchants.find_by!(name: "Internet Provider")
    restored_provider = @family.recurring_transactions.find_by!(merchant: restored_merchant)

    assert_equal restored_account, restored_provider.account
    assert_equal(-89.99, restored_provider.amount.to_f)
    assert_equal "USD", restored_provider.currency
    assert_equal 14, restored_provider.expected_day_of_month
    assert_equal Date.parse("2024-01-14"), restored_provider.last_occurrence_date
    assert_equal Date.parse("2024-02-14"), restored_provider.next_expected_date
    assert_equal "active", restored_provider.status
    assert_equal 6, restored_provider.occurrence_count
    assert_equal true, restored_provider.manual
    assert_equal(-95.0, restored_provider.expected_amount_min.to_f)
    assert_equal(-85.0, restored_provider.expected_amount_max.to_f)
    assert_equal(-89.99, restored_provider.expected_amount_avg.to_f)

    restored_named = @family.recurring_transactions.find_by!(name: "Quarterly Insurance")
    assert_nil restored_named.account
    assert_nil restored_named.merchant
    assert_equal 240.0, restored_named.amount.to_f
    assert_equal 28, restored_named.expected_day_of_month
    assert_equal Date.parse("2024-01-28"), restored_named.last_occurrence_date
    assert_equal Date.parse("2024-04-28"), restored_named.next_expected_date
    assert_equal "inactive", restored_named.status
    assert_equal 2, restored_named.occurrence_count
    assert_equal false, restored_named.manual
  end

  test "imports recurring transactions with unknown status fallback" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Main Checking",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Merchant",
        data: {
          id: "merchant-1",
          name: "Streaming Service"
        }
      },
      {
        type: "RecurringTransaction",
        data: {
          id: "recurring-1",
          account_id: "acct-1",
          merchant_id: "merchant-1",
          amount: "-15.99",
          currency: "USD",
          expected_day_of_month: "8",
          last_occurrence_date: "2024-01-08",
          next_expected_date: "2024-02-08",
          status: "bogus_status",
          occurrence_count: 2
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    recurring_transaction = @family.recurring_transactions.first
    assert_not_nil recurring_transaction
    assert_equal 8, recurring_transaction.expected_day_of_month
    assert_equal Date.parse("2024-01-08"), recurring_transaction.last_occurrence_date
    assert_equal Date.parse("2024-02-08"), recurring_transaction.next_expected_date
    assert_equal "active", recurring_transaction.status
  end

  test "skips recurring transactions with missing recurrence dates" do
    ndjson = build_ndjson([
      {
        type: "RecurringTransaction",
        data: {
          id: "recurring-1",
          amount: "-15.99",
          currency: "USD",
          expected_day_of_month: "8",
          last_occurrence_date: nil,
          status: "active",
          occurrence_count: 2,
          name: "Streaming Service"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    assert_equal 0, @family.recurring_transactions.count
  end

  test "skips recurring transactions when referenced account is missing" do
    ndjson = build_ndjson([
      {
        type: "RecurringTransaction",
        data: {
          id: "recurring-1",
          account_id: "missing-account",
          amount: "-89.99",
          currency: "USD",
          expected_day_of_month: 14,
          last_occurrence_date: "2024-01-14",
          next_expected_date: "2024-02-14",
          status: "active",
          name: "Internet Provider"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    assert_equal 0, @family.recurring_transactions.count
  end

  test "skips recurring transactions with blank expected day" do
    ndjson = build_ndjson([
      {
        type: "RecurringTransaction",
        data: {
          id: "recurring-1",
          amount: "-89.99",
          currency: "USD",
          expected_day_of_month: "",
          status: "active",
          name: "Internet Provider"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    assert_equal 0, @family.recurring_transactions.count
  end

  test "imports transactions with references" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "acct-1",
          name: "Main Account",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Category",
        data: {
          id: "cat-1",
          name: "Food",
          color: "#FF0000",
          classification: "expense"
        }
      },
      {
        type: "Tag",
        data: {
          id: "tag-1",
          name: "Essential"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "txn-1",
          account_id: "acct-1",
          date: "2024-01-15",
          amount: "-50.00",
          name: "Grocery Store",
          currency: "USD",
          category_id: "cat-1",
          tag_ids: [ "tag-1" ],
          notes: "Weekly groceries"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    assert_equal 1, result[:entry_ids].count

    transaction = @family.transactions.first
    assert_not_nil transaction
    assert_equal "Grocery Store", transaction.entry.name
    assert_equal -50.0, transaction.entry.amount.to_f
    assert_equal "Food", transaction.category.name
    assert_equal 1, transaction.tags.count
    assert_equal "Essential", transaction.tags.first.name
    assert_equal "Weekly groceries", transaction.entry.notes
  end

  test "imports native split lines and lets transfers reference split children" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "checking",
          name: "Checking",
          balance: "1000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Account",
        data: {
          id: "wallet",
          name: "Wallet",
          balance: "500",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Category",
        data: {
          id: "cat-fee",
          name: "Bank Fees",
          color: "#FF0000",
          classification: "expense"
        }
      },
      {
        type: "Tag",
        data: {
          id: "tag-imported",
          name: "Imported"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "split-parent",
          account_id: "checking",
          date: "2024-01-15",
          amount: "104.00",
          name: "ATM withdrawal plus fee",
          currency: "USD",
          tag_ids: [ "tag-imported" ],
          split_lines: [
            {
              id: "split-transfer-leg",
              amount: "100.00",
              name: "Cash movement",
              notes: "Transfer portion"
            },
            {
              id: "split-fee-line",
              amount: "4.00",
              name: "ATM fee",
              category_id: "cat-fee",
              notes: "Fee portion"
            }
          ]
        }
      },
      {
        type: "Transaction",
        data: {
          id: "wallet-inflow",
          account_id: "wallet",
          date: "2024-01-15",
          amount: "-100.00",
          name: "Cash received",
          currency: "USD"
        }
      },
      {
        type: "Transfer",
        data: {
          id: "transfer-1",
          inflow_transaction_id: "wallet-inflow",
          outflow_transaction_id: "split-transfer-leg",
          status: "confirmed",
          notes: "Split-linked transfer"
        }
      }
    ])

    result = Family::DataImporter.new(@family, ndjson).import!

    parent_entry = @family.entries.find_by!(name: "ATM withdrawal plus fee")
    assert parent_entry.split_parent?
    assert_equal true, parent_entry.excluded
    assert_equal 4, result[:entry_ids].count
    assert_includes result[:entry_ids], parent_entry.id

    transfer_child = parent_entry.child_entries.find_by!(name: "Cash movement")
    fee_child = parent_entry.child_entries.find_by!(name: "ATM fee")
    assert_equal "Transfer portion", transfer_child.notes
    assert_equal "Fee portion", fee_child.notes
    assert_equal "Bank Fees", fee_child.transaction.category.name
    assert_equal [ "Imported" ], transfer_child.transaction.tags.map(&:name)
    assert_equal [ "Imported" ], fee_child.transaction.tags.map(&:name)

    transfer = Transfer.find_by!(notes: "Split-linked transfer")
    assert_equal "confirmed", transfer.status
    assert_equal "Cash movement", transfer.outflow_transaction.entry.name
    assert_equal "Cash received", transfer.inflow_transaction.entry.name
  end

  test "imports split lines without adding omitted parent taxonomy to explicit empty values" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "checking",
          name: "Checking",
          balance: "1000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Tag",
        data: {
          id: "tag-parent",
          name: "Parent tag"
        }
      },
      {
        type: "Merchant",
        data: {
          id: "merchant-parent",
          name: "Parent merchant"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "split-parent",
          account_id: "checking",
          date: "2024-01-15",
          amount: "100.00",
          name: "Tagged merchant split",
          currency: "USD",
          merchant_id: "merchant-parent",
          tag_ids: [ "tag-parent" ],
          split_lines: [
            {
              id: "split-inherits",
              amount: "40.00",
              name: "Inherits omitted taxonomy"
            },
            {
              id: "split-empty",
              amount: "60.00",
              name: "Explicit empty taxonomy",
              merchant_id: nil,
              tag_ids: []
            }
          ]
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    parent_entry = @family.entries.find_by!(name: "Tagged merchant split")
    inherited_child = parent_entry.child_entries.find_by!(name: "Inherits omitted taxonomy")
    explicit_empty_child = parent_entry.child_entries.find_by!(name: "Explicit empty taxonomy")

    assert_equal "Parent merchant", inherited_child.transaction.merchant.name
    assert_equal [ "Parent tag" ], inherited_child.transaction.tags.map(&:name)
    assert_nil explicit_empty_child.transaction.merchant
    assert_empty explicit_empty_child.transaction.tags
  end

  # An export taken while a transaction carried a tag twice lists the tag id
  # twice, and the import must not fail on the unique index because of it.
  test "imports a repeated tag id once" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" } },
      { type: "Tag", data: { id: "tag-1", name: "Repeated" } },
      {
        type: "Transaction",
        data: {
          id: "plain", account_id: "checking", date: "2024-01-15", amount: "10.00",
          name: "Plain", currency: "USD", tag_ids: [ "tag-1", "tag-1" ]
        }
      },
      {
        type: "Transaction",
        data: {
          id: "split-parent", account_id: "checking", date: "2024-01-15", amount: "30.00",
          name: "Split parent", currency: "USD", tag_ids: [ "tag-1", "tag-1" ],
          split_lines: [
            { id: "inherits", amount: "10.00", name: "Inherits" },
            { id: "explicit", amount: "20.00", name: "Explicit", tag_ids: [ "tag-1", "tag-1" ] }
          ]
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    tag = @family.tags.find_by!(name: "Repeated")
    [ "Plain", "Inherits", "Explicit" ].each do |name|
      transaction = @family.entries.find_by!(name: name).transaction
      assert_equal [ tag.id ], transaction.taggings.pluck(:tag_id), "#{name} should carry the tag once"
    end
  end

  test "session transaction reimport only replaces current family taggings" do
    session = @family.import_sessions.create!(expected_chunks: 1)
    account = @family.accounts.create!(
      name: "Session Checking",
      accountable: Depository.new,
      balance: 100,
      currency: "USD"
    )
    original_tag = @family.tags.create!(name: "Original")
    replacement_tag = @family.tags.create!(name: "Replacement")
    entry = account.entries.create!(
      date: Date.parse("2024-01-01"),
      amount: -10,
      currency: "USD",
      name: "Original transaction",
      source: "sure_import_session:#{session.id}",
      external_id: "Transaction:txn-1",
      entryable: Transaction.new(kind: "standard")
    )
    transaction = entry.entryable
    transaction.taggings.create!(tag: original_tag)

    other_family = Family.create!(name: "Other Family", currency: "USD")
    other_session = other_family.import_sessions.create!(expected_chunks: 1)
    other_account = other_family.accounts.create!(
      name: "Other Checking",
      accountable: Depository.new,
      balance: 100,
      currency: "USD"
    )
    other_tag = other_family.tags.create!(name: "Other Original")
    other_entry = other_account.entries.create!(
      date: Date.parse("2024-01-01"),
      amount: -10,
      currency: "USD",
      name: "Other transaction",
      source: "sure_import_session:#{other_session.id}",
      external_id: "Transaction:txn-1",
      entryable: Transaction.new(kind: "standard")
    )
    other_transaction = other_entry.entryable
    other_transaction.taggings.create!(tag: other_tag)

    other_session.source_mappings.create!(
      family: other_family,
      source_type: "Transaction",
      source_id: "txn-1",
      target: other_transaction
    )

    session.source_mappings.create!(
      family: @family,
      source_type: "Account",
      source_id: "acct-1",
      target: account
    )
    session.source_mappings.create!(
      family: @family,
      source_type: "Tag",
      source_id: "tag-1",
      target: replacement_tag
    )
    session.source_mappings.create!(
      family: @family,
      source_type: "Transaction",
      source_id: "txn-1",
      target: transaction
    )

    ndjson = build_ndjson([
      {
        type: "Transaction",
        data: {
          id: "txn-1",
          account_id: "acct-1",
          tag_ids: [ "tag-1" ],
          date: "2024-02-01",
          amount: "-12.34",
          currency: "USD",
          name: "Updated transaction"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson, import_session: session).import!

    assert_equal [ "Replacement" ], transaction.reload.tags.map(&:name)
    assert_equal "Updated transaction", entry.reload.name
    assert_equal [ "Other Original" ], other_transaction.reload.tags.map(&:name)
    assert_equal "Other transaction", other_entry.reload.name
  end

  test "imports trades with securities" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "inv-acct-1",
          name: "Investment Account",
          balance: "10000",
          currency: "USD",
          accountable_type: "Investment"
        }
      },
      {
        type: "Trade",
        data: {
          id: "trade-1",
          account_id: "inv-acct-1",
          date: "2024-01-15",
          ticker: "AAPL",
          qty: "10",
          price: "150.00",
          amount: "-1500.00",
          currency: "USD"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    # Account + Opening balance + Trade entry
    assert_equal 1, result[:entry_ids].count

    trade = @family.trades.first
    assert_not_nil trade
    assert_equal "AAPL", trade.security.ticker
    assert_equal 10.0, trade.qty.to_f
    assert_equal 150.0, trade.price.to_f
  end

  test "imports holding snapshots with security identity" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "inv-acct-1",
          name: "Investment Account",
          balance: "10000",
          currency: "USD",
          accountable_type: "Investment"
        }
      },
      {
        type: "Holding",
        data: {
          id: "holding-1",
          account_id: "inv-acct-1",
          security_id: "security-1",
          ticker: "VTI",
          security_name: "Vanguard Total Stock Market ETF",
          exchange_operating_mic: "ARCX",
          country_code: "US",
          date: "2024-01-15",
          qty: "100",
          price: "250.25",
          amount: "25025.00",
          currency: "USD",
          cost_basis: "200.00",
          cost_basis_source: "manual",
          cost_basis_locked: true,
          security_locked: true
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Investment Account")
    holding = account.holdings.first

    assert_not_nil holding
    assert_equal Date.parse("2024-01-15"), holding.date
    assert_equal "VTI", holding.security.ticker
    assert_equal "Vanguard Total Stock Market ETF", holding.security.name
    assert_equal "ARCX", holding.security.exchange_operating_mic
    assert_equal 100.0, holding.qty.to_f
    assert_equal 250.25, holding.price.to_f
    assert_equal 25_025.0, holding.amount.to_f
    assert_equal 200.0, holding.cost_basis.to_f
    assert_equal "manual", holding.cost_basis_source
    assert holding.cost_basis_locked
    assert holding.security_locked

    opening_anchor = account.valuations.opening_anchor.first
    assert_equal Date.parse("2024-01-14"), opening_anchor.entry.date
  end

  test "imports duplicate holding snapshots idempotently by account security date and currency" do
    holding_record = {
      type: "Holding",
      data: {
        id: "holding-1",
        account_id: "inv-acct-1",
        security_id: "security-1",
        ticker: "VTI",
        security_name: "Vanguard Total Stock Market ETF",
        exchange_operating_mic: "ARCX",
        kind: "unsupported",
        date: "2024-01-15",
        qty: "100",
        price: "250.25",
        amount: "25025.00",
        currency: "USD"
      }
    }

    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "inv-acct-1",
          name: "Investment Account",
          balance: "10000",
          currency: "USD",
          accountable_type: "Investment"
        }
      },
      holding_record,
      holding_record.deep_merge(data: { id: "holding-1-duplicate", qty: "101", amount: "25275.25" })
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Investment Account")
    assert_equal 1, account.holdings.count

    holding = account.holdings.first
    assert_equal 101.0, holding.qty.to_f
    assert_equal 25_275.25, holding.amount.to_f
    assert_equal "standard", holding.security.kind
  end

  test "imports same holding date in different currencies separately" do
    holding_record = {
      type: "Holding",
      data: {
        id: "holding-1",
        account_id: "inv-acct-1",
        security_id: "security-1",
        ticker: "VTI",
        security_name: "Vanguard Total Stock Market ETF",
        exchange_operating_mic: "ARCX",
        date: "2024-01-15",
        qty: "100",
        price: "250.25",
        amount: "25025.00",
        currency: "USD"
      }
    }

    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "inv-acct-1",
          name: "Investment Account",
          balance: "10000",
          currency: "USD",
          accountable_type: "Investment"
        }
      },
      holding_record,
      holding_record.deep_merge(data: { id: "holding-2", currency: "CAD", amount: "34034.00" })
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Investment Account")
    assert_equal 2, account.holdings.count
    assert_equal %w[CAD USD], account.holdings.order(:currency).pluck(:currency)
  end

  test "round trips holding snapshots through full export" do
    source_family = Family.create!(
      name: "Source Family",
      currency: "USD",
      locale: "en",
      date_format: "%Y-%m-%d"
    )
    source_account = source_family.accounts.create!(
      name: "Round Trip Investment",
      accountable: Investment.new,
      balance: 25_000,
      currency: "USD"
    )
    source_security = Security.create!(
      ticker: "VTI#{SecureRandom.hex(4).upcase}",
      name: "Vanguard Total Stock Market ETF",
      country_code: "US",
      exchange_operating_mic: "ARCX"
    )
    source_account.holdings.create!(
      security: source_security,
      date: Date.parse("2024-01-15"),
      qty: 100,
      price: 250.25,
      amount: 25_025,
      currency: "USD",
      cost_basis: 200,
      cost_basis_source: "manual",
      cost_basis_locked: true,
      security_locked: true
    )

    zip_data = Family::DataExporter.new(source_family).generate_export
    ndjson = nil
    Zip::File.open_buffer(zip_data) do |zip|
      ndjson = zip.read("all.ndjson")
    end

    Family::DataImporter.new(@family, ndjson).import!

    imported_account = @family.accounts.find_by!(name: "Round Trip Investment")
    imported_holding = imported_account.holdings.find_by!(date: Date.parse("2024-01-15"))

    assert_equal source_security.ticker, imported_holding.security.ticker
    assert_equal "ARCX", imported_holding.security.exchange_operating_mic
    assert_equal 100.0, imported_holding.qty.to_f
    assert_equal 250.25, imported_holding.price.to_f
    assert_equal 25_025.0, imported_holding.amount.to_f
    assert_equal 200.0, imported_holding.cost_basis.to_f
    assert_equal "manual", imported_holding.cost_basis_source
    assert imported_holding.cost_basis_locked
    assert imported_holding.security_locked
  end

  # Derived lots are rebuilt on every sync, so the file carries only what the
  # user chose: a lot's cost, the lot a sale names, and the account's method.
  test "export then import round-trips a user-set lot basis and a named lot" do
    Family::DataImporter.new(@family, lot_export).import!

    account = @family.accounts.find_by!(name: "Lot Round Trip")
    Holding::Materializer.new(account, strategy: :forward).materialize_holdings
    trades = lot_trades(account)

    assert_equal "fifo", account.cost_basis_method
    assert_equal trades.fetch(40), trades.fetch(-10).trade.lot_source_entry, "the sale's named lot"
    lot = HoldingLot.find_by!(source_entry: trades.fetch(60))
    assert_equal 600, lot.manual_total_cost
    assert_equal 10, lot.unit_cost, "the user's 600 over 60 units, after re-materialization"
    assert_equal [ 60, 30 ], HoldingLot.where(account: account).order(:acquired_on).pluck(:qty).map(&:to_i), "the sale took the named lot, not the oldest"
  end

  # An account that sells by average keeps a stored choice and ignores it, so
  # an export taken after a switch still carries it.
  test "a named lot kept through a switch to average imports without failing the import" do
    Family::DataImporter.new(@family, lot_export(switch_to: "average")).import!

    account = @family.accounts.find_by!(name: "Lot Round Trip")
    trades = lot_trades(account)
    assert_equal "average", account.cost_basis_method
    assert_equal trades.fetch(40), trades.fetch(-10).trade.reload.lot_source_entry
  end

  test "a sale and the lot it names restore their link when each arrives in its own chunk" do
    lines = lot_export.split("\n")
    session = @family.import_sessions.create!(expected_chunks: lines.size)

    lines.each { |line| Family::DataImporter.new(@family, line, import_session: session).import! }

    trades = lot_trades(@family.accounts.find_by!(name: "Lot Round Trip"))
    assert_equal trades.fetch(40), trades.fetch(-10).trade.reload.lot_source_entry
    assert_equal 600, HoldingLot.find_by!(source_entry: trades.fetch(60)).manual_total_cost
  end

  # An import stamps entries in file order, so the file's order of a day's
  # trades becomes the order they replay in.
  test "a fifo round trip replays a day's trades in the order they were entered" do
    assert_equal 180, round_trip_cost_basis("fifo", [ [ 10, 100 ], [ 20, 200 ], [ -5, 100 ] ]),
      "the sale took the 10 at $100 entered first, leaving 5 at $100 and 20 at $200"
  end

  test "an average round trip replays a sell-off before a same-day repurchase entered after it" do
    assert_equal 20, round_trip_cost_basis("average", [ [ 1, 10 ], [ -1, 10 ], [ 1, 20 ] ]),
      "the sale closed the position, so the repurchase starts a fresh basis"
  end

  # Replay puts a same-day trade entered later after the sale, so the sale
  # cannot have sold from it.
  test "a same-day lot listed after the sale that names it is dropped and counted" do
    lines = lot_export.split("\n")
    trade_lines = lines.select { |line| JSON.parse(line)["type"] == "Trade" }
    sale_line = trade_lines.find { |line| JSON.parse(line).dig("data", "lot_source_trade_id") }
    lot_line = trade_lines.find { |line| JSON.parse(line).dig("data", "id") == JSON.parse(sale_line).dig("data", "lot_source_trade_id") }
    assert_operator lines.index(lot_line), :<, lines.index(sale_line), "precondition: the export lists the lot first"

    { "lot listed first" => lines, "sale listed first" => lines.map { |line| { lot_line => sale_line, sale_line => lot_line }.fetch(line, line) } }
      .each do |label, ordered|
        family = Family.create!(name: "Target #{label}", currency: "USD", locale: "en", date_format: "%Y-%m-%d")
        result = Family::DataImporter.new(family, ordered.join("\n")).import!
        sale = lot_trades(family.accounts.find_by!(name: "Lot Round Trip")).fetch(-10).trade

        if label == "lot listed first"
          assert_equal JSON.parse(lot_line).dig("data", "date"), JSON.parse(sale_line).dig("data", "date"), "precondition: bought the sale's day"
          assert_not_nil sale.lot_source_entry_id, label
          assert_equal 0, result[:summary].dig("trades", "skipped").to_i, label
        else
          assert_nil sale.lot_source_entry_id, label
          assert_equal 1, result[:summary].dig("trades", "skipped"), label
        end
      end
  end

  test "an unusable lot cost or lot name is dropped and counted, and the trade still imports" do
    # Each edit names the check that tells its drop from a clean import, where
    # the first buy's lot carries the user's 600 and the sale names the $20 lot.
    cases = {
      "a non-numeric cost" => [ ->(data) { data["lot_total_cost"] = "abc" if data["lot_total_cost"] }, :no_lot_cost ],
      "a negative cost" => [ ->(data) { data["lot_total_cost"] = "-5" if data["lot_total_cost"] }, :no_lot_cost ],
      "a cost on a sale" => [ ->(data) { data["lot_total_cost"] = "50" if data["qty"].to_d.negative? }, :only_the_buys_lot ],
      "an unknown named lot" => [ ->(data) { data["lot_source_trade_id"] = SecureRandom.uuid if data["lot_source_trade_id"] }, :no_choice ],
      "a sale naming itself" => [ ->(data) { data["lot_source_trade_id"] = data["id"] if data["lot_source_trade_id"] }, :no_choice ],
      "a sale dated before its lot" => [ ->(data) { data["date"] = 5.days.ago.to_date.iso8601 if data["lot_source_trade_id"] }, :no_choice ],
      "a sale of another security" => [ ->(data) { data.merge!("security_id" => SecureRandom.uuid, "ticker" => "OTHER#{SecureRandom.hex(2).upcase}") if data["lot_source_trade_id"] }, :no_choice ]
    }

    cases.each do |label, (edit, check)|
      family = Family.create!(name: "Target #{label}", currency: "USD", locale: "en", date_format: "%Y-%m-%d")

      result = Family::DataImporter.new(family, edit_trades(lot_export) { |data| edit.call(data) }).import!

      account = family.accounts.find_by!(name: "Lot Round Trip")
      trades = lot_trades(account)
      assert_equal 3, trades.size, "#{label}: a trade was lost"
      assert_equal 1, result[:summary].dig("trades", "skipped"), label
      case check
      when :no_lot_cost
        assert_equal 0, HoldingLot.where(account: account).count, "#{label}: the cost was seeded"
      when :only_the_buys_lot
        assert_equal [ trades.fetch(60).id ], HoldingLot.where(account: account).pluck(:source_entry_id), "#{label}: a sale got a lot"
      when :no_choice
        assert_nil trades.fetch(-10).trade.reload.lot_source_entry_id, "#{label}: the choice was stored"
        assert_equal 600, HoldingLot.find_by!(source_entry: trades.fetch(60)).manual_total_cost, "#{label}: the lot's cost went with it"
      end
    end
  end

  # A sale the user has since marked a transfer out names no lot, as the
  # drawer would not let it.
  # Labels are not in the export, so only a sale the user marked a transfer
  # out after a session's first import can meet this; the session refuses it.
  test "a session re-import refuses a named lot on a sale marked a transfer out" do
    session = @family.import_sessions.create!(expected_chunks: 2)
    export = lot_export
    Family::DataImporter.new(@family, export, import_session: session).import!
    trades = lot_trades(@family.accounts.find_by!(name: "Lot Round Trip"))
    sale = trades.fetch(-10).trade
    assert_equal trades.fetch(40).id, sale.lot_source_entry_id, "precondition: the first import named the lot"
    sale.update_columns(investment_activity_label: Trade::TRANSFER_LABEL)

    assert_raises(Family::DataImporter::InvalidRecordError) do
      Family::DataImporter.new(@family, export, import_session: session).import!
    end
  end

  test "a session import raises on an unusable lot cost" do
    session = @family.import_sessions.create!(expected_chunks: 1)

    assert_raises(Family::DataImporter::InvalidRecordError) do
      Family::DataImporter.new(@family, edit_trades(lot_export) { |data| data["lot_total_cost"] = "abc" if data["lot_total_cost"] }, import_session: session).import!
    end
  end

  test "re-importing without the cost method keeps the account's own, and without a lot's cost or name clears them" do
    session = @family.import_sessions.create!(expected_chunks: 2)
    export = lot_export
    Family::DataImporter.new(@family, export, import_session: session).import!

    cleared = edit_trades(export) { |data| data["lot_total_cost"] = nil; data["lot_source_trade_id"] = nil }
    cleared = cleared.split("\n").map { |line| JSON.parse(line) }.each { |record| record["data"].delete("cost_basis_method") if record["type"] == "Account" }.map(&:to_json).join("\n")
    Family::DataImporter.new(@family, cleared, import_session: session).import!

    account = @family.accounts.find_by!(name: "Lot Round Trip")
    trades = lot_trades(account)
    assert_equal 1, @family.accounts.where(name: "Lot Round Trip").count, "precondition: the re-import updated the account"
    assert_equal "fifo", account.cost_basis_method
    assert_nil HoldingLot.find_by!(source_entry: trades.fetch(60)).manual_total_cost
    assert_nil trades.fetch(-10).trade.reload.lot_source_entry_id
  end

  test "round trips property details and address through full export" do
    source_family = Family.create!(name: "Source Property Family", currency: "USD", locale: "en", date_format: "%Y-%m-%d")
    source_family.accounts.create!(
      name: "Round Trip Land",
      balance: 150_000_000,
      currency: "PYG",
      accountable: Property.new(
        subtype: "plot",
        year_built: 2001,
        area_value: 12_000,
        area_unit: "sqm",
        address: Address.new(line1: "Ruta 2 km 40", locality: "Caacupe", region: "Cordillera", postal_code: "3000", country: "PY")
      )
    )

    zip_data = Family::DataExporter.new(source_family).generate_export
    ndjson = nil
    Zip::File.open_buffer(zip_data) { |zip| ndjson = zip.read("all.ndjson") }

    Family::DataImporter.new(@family, ndjson).import!

    property = @family.accounts.find_by!(name: "Round Trip Land").accountable
    assert_equal "plot", property.subtype
    assert_equal 2001, property.year_built
    assert_equal 12_000, property.area_value
    assert_equal "sqm", property.area_unit

    address = property.address
    assert_not_nil address, "the address should survive a backup and restore"
    assert_equal "Ruta 2 km 40", address.line1
    assert_equal "Caacupe", address.locality
    assert_equal "Cordillera", address.region
    assert_equal "3000", address.postal_code
    assert_equal "PY", address.country
  end

  test "imports property details from an export without an address" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-property-1",
          name: "Imported Land",
          balance: "1000",
          currency: "USD",
          accountable_type: "Property",
          accountable: { subtype: "agri_land", year_built: nil, area_value: 50, area_unit: "sqm", id: "ignored", avm_provider: "rentcast" }
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    property = @family.accounts.find_by!(name: "Imported Land").accountable
    assert_equal 50, property.area_value
    assert_equal "sqm", property.area_unit
    assert_nil property.year_built
    assert_nil property.avm_provider, "provider links are not restored"
    assert_nil property.address
  end

  test "an explicit null property detail keeps the default" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "old-property-2",
          name: "Null Unit Land",
          balance: "1000",
          currency: "USD",
          accountable_type: "Property",
          accountable: { subtype: "plot", area_value: 50, area_unit: nil }
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    property = @family.accounts.find_by!(name: "Null Unit Land").accountable
    assert_equal 50, property.area_value
    assert_equal "sqft", property.area_unit
  end

  test "round trips raw balance history through full export" do
    source_family = Family.create!(
      name: "Source Balance Family",
      currency: "USD",
      locale: "en",
      date_format: "%Y-%m-%d"
    )
    source_account = source_family.accounts.create!(
      name: "Round Trip Balance Checking",
      accountable: Depository.new,
      balance: 1_500,
      currency: "USD"
    )
    source_account.balances.create!(
      date: Date.parse("2024-01-31"),
      balance: 1_500,
      cash_balance: 1_450,
      currency: "USD",
      start_cash_balance: 1_000,
      start_non_cash_balance: 0,
      cash_inflows: 700,
      cash_outflows: 250,
      non_cash_inflows: 0,
      non_cash_outflows: 0,
      net_market_flows: 0,
      cash_adjustments: 0,
      non_cash_adjustments: 0,
      flows_factor: 1
    )

    zip_data = Family::DataExporter.new(source_family).generate_export
    ndjson = nil
    Zip::File.open_buffer(zip_data) do |zip|
      ndjson = zip.read("all.ndjson")
    end

    Family::DataImporter.new(@family, ndjson).import!

    imported_account = @family.accounts.find_by!(name: "Round Trip Balance Checking")
    imported_balance = imported_account.balances.find_by!(date: Date.parse("2024-01-31"), currency: "USD")

    assert_equal 1500.0, imported_balance.balance.to_f
    assert_equal 1450.0, imported_balance.cash_balance.to_f
    assert_equal 1000.0, imported_balance.start_cash_balance.to_f
    assert_equal 700.0, imported_balance.cash_inflows.to_f
    assert_equal 250.0, imported_balance.cash_outflows.to_f
  end

  test "imports holding snapshots with ticker fallback when exchange mic is missing" do
    existing_security = Security.create!(
      ticker: "VTI",
      name: "Existing VTI",
      exchange_operating_mic: "ARCX"
    )

    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "inv-acct-1",
          name: "Investment Account",
          balance: "10000",
          currency: "USD",
          accountable_type: "Investment"
        }
      },
      {
        type: "Holding",
        data: {
          id: "holding-1",
          account_id: "inv-acct-1",
          ticker: "VTI",
          security_name: "Imported VTI",
          date: "2024-01-15",
          qty: "100",
          price: "250.25",
          amount: "25025.00",
          currency: "USD",
          cost_basis_locked: false,
          security_locked: false
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    holding = @family.accounts.find_by!(name: "Investment Account").holdings.first
    assert_equal existing_security, holding.security
    assert_equal 1, Security.where(ticker: "VTI").count
  end

  test "updates cached security with safe holding metadata" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "inv-acct-1",
          name: "Investment Account",
          balance: "10000",
          currency: "USD",
          accountable_type: "Investment"
        }
      },
      {
        type: "Trade",
        data: {
          id: "trade-1",
          account_id: "inv-acct-1",
          security_id: "security-1",
          ticker: "VTI",
          date: "2024-01-10",
          qty: "10",
          price: "250.00",
          amount: "-2500.00",
          currency: "USD"
        }
      },
      {
        type: "Holding",
        data: {
          id: "holding-1",
          account_id: "inv-acct-1",
          security_id: "security-1",
          ticker: "VTI",
          security_name: "Vanguard Total Stock Market ETF",
          exchange_operating_mic: "ARCX",
          country_code: "US",
          website_url: "https://investor.vanguard.com",
          date: "2024-01-15",
          qty: "100",
          price: "250.25",
          amount: "25025.00",
          currency: "USD",
          cost_basis_locked: false,
          security_locked: false
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    security = @family.holdings.first.security
    assert_equal "Vanguard Total Stock Market ETF", security.name
    assert_equal "ARCX", security.exchange_operating_mic
    assert_equal "US", security.country_code
    assert_equal "https://investor.vanguard.com", security.website_url
  end

  test "imports valuations" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "prop-acct-1",
          name: "Property",
          balance: "500000",
          currency: "USD",
          accountable_type: "Property"
        }
      },
      {
        type: "Valuation",
        data: {
          id: "val-1",
          account_id: "prop-acct-1",
          date: "2024-06-15",
          amount: "520000",
          name: "Updated valuation",
          currency: "USD"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    assert_equal 1, result[:entry_ids].count

    account = @family.accounts.find_by(name: "Property")
    valuation = account.valuations.joins(:entry).find_by(entries: { name: "Updated valuation" })
    assert_not_nil valuation
    assert_equal 520000.0, valuation.entry.amount.to_f
  end

  test "imports unknown valuation kinds as reconciliations" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "prop-acct-1",
          name: "Property",
          balance: "500000",
          currency: "USD",
          accountable_type: "Property"
        }
      },
      {
        type: "Valuation",
        data: {
          id: "val-1",
          account_id: "prop-acct-1",
          date: "2024-06-15",
          amount: "520000",
          name: "Updated valuation",
          currency: "USD",
          kind: "legacy_unknown_kind"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    account = @family.accounts.find_by!(name: "Property")
    valuation = account.valuations.joins(:entry).find_by!(entries: { name: "Updated valuation" })
    assert_equal "reconciliation", valuation.kind
  end

  test "imports transfer decisions and rejected transfers with remapped transactions" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "checking",
          name: "Checking",
          balance: "1000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Account",
        data: {
          id: "savings",
          name: "Savings",
          balance: "2500",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "transfer-outflow",
          account_id: "checking",
          date: "2024-01-15",
          amount: "100.00",
          name: "Transfer to savings",
          currency: "USD",
          kind: "standard"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "transfer-inflow",
          account_id: "savings",
          date: "2024-01-15",
          amount: "-100.00",
          name: "Transfer from checking",
          currency: "USD",
          kind: "standard"
        }
      },
      {
        type: "Transfer",
        data: {
          id: "transfer-1",
          inflow_transaction_id: "transfer-inflow",
          outflow_transaction_id: "transfer-outflow",
          status: "confirmed",
          notes: "Confirmed by user"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "rejected-outflow",
          account_id: "checking",
          date: "2024-01-20",
          amount: "25.00",
          name: "Candidate outflow",
          currency: "USD",
          kind: "standard"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "rejected-inflow",
          account_id: "savings",
          date: "2024-01-20",
          amount: "-25.00",
          name: "Candidate inflow",
          currency: "USD",
          kind: "standard"
        }
      },
      {
        type: "RejectedTransfer",
        data: {
          id: "rejected-transfer-1",
          inflow_transaction_id: "rejected-inflow",
          outflow_transaction_id: "rejected-outflow"
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    transfer = Transfer.find_by!(notes: "Confirmed by user")
    assert_not_nil transfer
    assert_equal "confirmed", transfer.status
    assert_equal "Confirmed by user", transfer.notes
    assert_equal "Transfer from checking", transfer.inflow_transaction.entry.name
    assert_equal "Transfer to savings", transfer.outflow_transaction.entry.name
    assert_equal "funds_movement", transfer.inflow_transaction.kind
    assert_equal "funds_movement", transfer.outflow_transaction.kind

    rejected_transfer = RejectedTransfer
      .joins(inflow_transaction: :entry)
      .find_by!(entries: { name: "Candidate inflow" })
    assert_not_nil rejected_transfer
    assert_equal "Candidate inflow", rejected_transfer.inflow_transaction.entry.name
    assert_equal "Candidate outflow", rejected_transfer.outflow_transaction.entry.name
  end

  test "restores a transfer the user made a plain transfer instead of an investment contribution" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" } },
      { type: "Account", data: { id: "brokerage", name: "Brokerage", balance: "2500", currency: "USD", accountable_type: "Investment" } },
      { type: "Transaction", data: { id: "fx-outflow", account_id: "checking", date: "2024-01-15", amount: "100.00", name: "To brokerage", currency: "USD", kind: "funds_movement" } },
      { type: "Transaction", data: { id: "fx-inflow", account_id: "brokerage", date: "2024-01-15", amount: "-100.00", name: "From checking", currency: "USD", kind: "funds_movement" } },
      { type: "Transfer", data: { id: "transfer-1", inflow_transaction_id: "fx-inflow", outflow_transaction_id: "fx-outflow", status: "confirmed", investment_contribution: false } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    outflow = Transaction.joins(:entry).find_by!(entries: { name: "To brokerage" })
    assert_equal "funds_movement", outflow.kind
    assert_nil outflow.category
    assert outflow.locked?(:kind)
    assert_equal false, outflow.transfer_as_outflow.investment_contribution_choice
  end

  test "imports a pending transfer without applying transfer kinds" do
    ndjson = build_ndjson([
      { type: "Account", data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" } },
      { type: "Account", data: { id: "savings", name: "Savings", balance: "2500", currency: "USD", accountable_type: "Depository" } },
      { type: "Transaction", data: { id: "pending-outflow", account_id: "checking", date: "2024-01-15", amount: "100.00", name: "Pending outflow", currency: "USD", kind: "standard" } },
      { type: "Transaction", data: { id: "pending-inflow", account_id: "savings", date: "2024-01-15", amount: "-100.00", name: "Pending inflow", currency: "USD", kind: "standard" } },
      { type: "Transfer", data: { id: "transfer-1", inflow_transaction_id: "pending-inflow", outflow_transaction_id: "pending-outflow", status: "pending" } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    transfer = Transfer.joins(inflow_transaction: :entry).find_by!(entries: { name: "Pending inflow" })
    assert transfer.pending?
    assert_equal "standard", transfer.inflow_transaction.kind
    assert_equal "standard", transfer.outflow_transaction.kind
  end

  test "skips rejected transfers with missing transactions under strict import" do
    session = @family.import_sessions.create!(expected_chunks: 1)

    ndjson = build_ndjson([
      {
        type: "Account",
        data: { id: "checking", name: "Checking", balance: "1000", currency: "USD", accountable_type: "Depository" }
      },
      {
        type: "Account",
        data: { id: "savings", name: "Savings", balance: "2500", currency: "USD", accountable_type: "Depository" }
      },
      {
        type: "Transaction",
        data: { id: "rejected-outflow", account_id: "checking", date: "2024-01-20", amount: "25.00", name: "Candidate outflow", currency: "USD", kind: "standard" }
      },
      {
        type: "Transaction",
        data: { id: "rejected-inflow", account_id: "savings", date: "2024-01-20", amount: "-25.00", name: "Candidate inflow", currency: "USD", kind: "standard" }
      },
      {
        type: "RejectedTransfer",
        data: { id: "rejected-valid", inflow_transaction_id: "rejected-inflow", outflow_transaction_id: "rejected-outflow" }
      },
      {
        type: "RejectedTransfer",
        data: { id: "rejected-orphan", inflow_transaction_id: "rejected-inflow", outflow_transaction_id: "missing-outflow" }
      }
    ])

    result = nil
    assert_difference -> { RejectedTransfer.count }, 1 do
      result = Family::DataImporter.new(@family, ndjson, import_session: session).import!
    end

    assert_equal 1, result[:summary].dig("rejected_transfers", "created")
    assert_equal 1, result[:summary].dig("rejected_transfers", "skipped")
  end

  test "imports duplicate transfer decisions idempotently with unknown status fallback" do
    ndjson = build_ndjson([
      {
        type: "Account",
        data: {
          id: "checking",
          name: "Checking",
          balance: "1000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Account",
        data: {
          id: "savings",
          name: "Savings",
          balance: "2500",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "transfer-outflow",
          account_id: "checking",
          date: "2024-01-15",
          amount: "100.00",
          name: "Transfer to savings",
          currency: "USD",
          kind: "funds_movement"
        }
      },
      {
        type: "Transaction",
        data: {
          id: "transfer-inflow",
          account_id: "savings",
          date: "2024-01-15",
          amount: "-100.00",
          name: "Transfer from checking",
          currency: "USD",
          kind: "funds_movement"
        }
      },
      {
        type: "Transfer",
        data: {
          id: "transfer-1",
          inflow_transaction_id: "transfer-inflow",
          outflow_transaction_id: "transfer-outflow",
          status: "settled"
        }
      },
      {
        type: "Transfer",
        data: {
          id: "transfer-1-duplicate",
          inflow_transaction_id: "transfer-inflow",
          outflow_transaction_id: "transfer-outflow",
          status: "settled"
        }
      }
    ])

    fallback_logs = []

    Rails.logger.stubs(:debug).with do |*args|
      message = args.first
      fallback_logs << message if message.to_s.include?("Unknown transfer status")
      true
    end

    assert_difference("Transfer.count", 1) do
      Family::DataImporter.new(@family, ndjson).import!
    end

    assert_equal [ 'Unknown transfer status "settled"; defaulting to pending' ], fallback_logs

    imported_transfer = Transfer
      .joins(inflow_transaction: :entry)
      .find_by!(entries: { name: "Transfer from checking" })
    assert_equal "pending", imported_transfer.status
  end

  test "imports budgets" do
    ndjson = build_ndjson([
      {
        type: "Budget",
        data: {
          id: "budget-1",
          start_date: "2024-01-01",
          end_date: "2024-01-31",
          budgeted_spending: "3000.00",
          expected_income: "5000.00",
          currency: "USD"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    budget = @family.budgets.first
    assert_not_nil budget
    assert_equal Date.parse("2024-01-01"), budget.start_date
    assert_equal Date.parse("2024-01-31"), budget.end_date
    assert_equal 3000.0, budget.budgeted_spending.to_f
    assert_equal 5000.0, budget.expected_income.to_f
  end

  test "imports budget_categories" do
    ndjson = build_ndjson([
      {
        type: "Category",
        data: {
          id: "cat-groceries",
          name: "Groceries",
          color: "#00FF00",
          classification: "expense"
        }
      },
      {
        type: "Budget",
        data: {
          id: "budget-1",
          start_date: "2024-01-01",
          end_date: "2024-01-31",
          budgeted_spending: "3000.00",
          expected_income: "5000.00",
          currency: "USD"
        }
      },
      {
        type: "BudgetCategory",
        data: {
          id: "bc-1",
          budget_id: "budget-1",
          category_id: "cat-groceries",
          budgeted_spending: "500.00",
          rollover_enabled: true,
          currency: "USD"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    budget = @family.budgets.first
    budget_category = budget.budget_categories.first
    assert_not_nil budget_category
    assert_equal "Groceries", budget_category.category.name
    assert_equal 500.0, budget_category.budgeted_spending.to_f
    assert budget_category.rollover_enabled?
  end

  test "imports a budget_category with only its required fields" do
    ndjson = build_ndjson([
      { type: "Category", data: { id: "cat-groceries", name: "Groceries", color: "#00FF00", classification: "expense" } },
      { type: "Budget", data: { id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31", currency: "USD" } },
      { type: "BudgetCategory", data: { id: "bc-1", budget_id: "budget-1", category_id: "cat-groceries" } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    budget_category = @family.budgets.first.budget_categories.first
    assert_equal 0, budget_category.budgeted_spending
    assert_not budget_category.rollover_enabled?
  end

  test "keeps the stored amount and rollover of a budget category when a later line omits them" do
    ndjson = build_ndjson([
      { type: "Category", data: { id: "cat-groceries", name: "Groceries", color: "#00FF00", classification: "expense" } },
      { type: "Budget", data: { id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31", currency: "USD" } },
      { type: "BudgetCategory", data: { id: "bc-1", budget_id: "budget-1", category_id: "cat-groceries", budgeted_spending: "500.00", rollover_enabled: true } },
      { type: "BudgetCategory", data: { id: "bc-2", budget_id: "budget-1", category_id: "cat-groceries" } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    budget_category = @family.budgets.first.budget_categories.first
    assert_equal 500, budget_category.budgeted_spending
    assert budget_category.rollover_enabled?
  end

  test "treats a blank rollover_enabled as absent" do
    ndjson = build_ndjson([
      { type: "Category", data: { id: "cat-groceries", name: "Groceries", color: "#00FF00", classification: "expense" } },
      { type: "Budget", data: { id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31", currency: "USD" } },
      { type: "BudgetCategory", data: { id: "bc-1", budget_id: "budget-1", category_id: "cat-groceries", budgeted_spending: "500.00", rollover_enabled: true } },
      { type: "BudgetCategory", data: { id: "bc-2", budget_id: "budget-1", category_id: "cat-groceries", rollover_enabled: "" } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    assert @family.budgets.first.budget_categories.first.rollover_enabled?
  end

  test "recomputes the carried-over amount of restored rollover budgets" do
    ndjson = build_ndjson([
      { type: "Category", data: { id: "cat-groceries", name: "Groceries", color: "#00FF00", classification: "expense" } },
      { type: "Budget", data: { id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31", budgeted_spending: "500.00", expected_income: "1000.00", currency: "USD" } },
      { type: "Budget", data: { id: "budget-2", start_date: "2024-02-01", end_date: "2024-02-29", budgeted_spending: "500.00", expected_income: "1000.00", currency: "USD" } },
      { type: "BudgetCategory", data: { id: "bc-1", budget_id: "budget-1", category_id: "cat-groceries", budgeted_spending: "500.00", rollover_enabled: true } },
      { type: "BudgetCategory", data: { id: "bc-2", budget_id: "budget-2", category_id: "cat-groceries", budgeted_spending: "500.00", rollover_enabled: true } }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    february = @family.budgets.find_by!(start_date: Date.new(2024, 2, 1))
    assert_equal 500, february.budget_categories.first.rolled_over_amount
  end

  test "keeps the import when recomputing rollover amounts fails, and logs it" do
    ndjson = build_ndjson([
      { type: "Category", data: { id: "cat-groceries", name: "Groceries", color: "#00FF00", classification: "expense" } },
      { type: "Budget", data: { id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31", budgeted_spending: "500.00", expected_income: "1000.00", currency: "USD" } },
      { type: "BudgetCategory", data: { id: "bc-1", budget_id: "budget-1", category_id: "cat-groceries", budgeted_spending: "500.00", rollover_enabled: true } }
    ])
    Budget::RolloverCalculator.any_instance.stubs(:recompute!).raises(StandardError, "boom")

    assert_difference -> { DebugLogEntry.where(family: @family, category: "import").count }, 1 do
      Family::DataImporter.new(@family, ndjson).import!
    end

    assert @family.budgets.first.budget_categories.first.rollover_enabled?
  end

  test "reuses an untouched default budget for the same period" do
    category = @family.categories.create!(name: "Groceries", color: "#00FF00")
    default_budget = @family.budgets.create!(
      start_date: Date.parse("2024-01-01"), end_date: Date.parse("2024-01-31"), currency: "USD"
    )
    default_budget.budget_categories.create!(category: category, budgeted_spending: 0, currency: "USD")

    ndjson = build_ndjson([
      { type: "Category", data: { id: "cat-groceries", name: "Groceries", color: "#00FF00", classification: "expense" } },
      {
        type: "Budget",
        data: {
          id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31",
          budgeted_spending: "3000.00", expected_income: "5000.00", currency: "USD"
        }
      },
      {
        type: "BudgetCategory",
        data: { id: "bc-1", budget_id: "budget-1", category_id: "cat-groceries", budgeted_spending: "500.00", currency: "USD" }
      }
    ])

    assert_no_difference -> { @family.budgets.count } do
      Family::DataImporter.new(@family, ndjson).import!
    end

    default_budget.reload
    assert_equal 3000.0, default_budget.budgeted_spending.to_f
    assert_equal 5000.0, default_budget.expected_income.to_f
    assert_equal 500.0, default_budget.budget_categories.find_by!(category: category).budgeted_spending.to_f
  end

  test "does not overwrite a populated budget for the same period" do
    @family.budgets.create!(
      start_date: Date.parse("2024-01-01"), end_date: Date.parse("2024-01-31"),
      budgeted_spending: 1200, expected_income: 2000, currency: "USD"
    )

    ndjson = build_ndjson([
      {
        type: "Budget",
        data: {
          id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31",
          budgeted_spending: "3000.00", expected_income: "5000.00", currency: "USD"
        }
      }
    ])

    assert_raises(ActiveRecord::RecordInvalid) { Family::DataImporter.new(@family, ndjson).import! }
    assert_equal 1200.0, @family.budgets.first.budgeted_spending.to_f
  end

  test "does not overwrite a budget the user explicitly set to zero" do
    @family.budgets.create!(
      start_date: Date.parse("2024-01-01"), end_date: Date.parse("2024-01-31"),
      budgeted_spending: 0, expected_income: 0, currency: "USD"
    )

    ndjson = build_ndjson([
      {
        type: "Budget",
        data: {
          id: "budget-1", start_date: "2024-01-01", end_date: "2024-01-31",
          budgeted_spending: "3000.00", expected_income: "5000.00", currency: "USD"
        }
      }
    ])

    assert_raises(ActiveRecord::RecordInvalid) { Family::DataImporter.new(@family, ndjson).import! }
    assert_equal 0.0, @family.budgets.first.budgeted_spending.to_f
  end

  test "does not reuse the household default for an exported personal budget" do
    default_budget = @family.budgets.create!(
      start_date: Date.parse("2024-01-01"), end_date: Date.parse("2024-01-31"), currency: "USD"
    )

    ndjson = build_ndjson([
      {
        type: "Budget",
        data: {
          id: "budget-1", user_id: "old-user-1", start_date: "2024-01-01", end_date: "2024-01-31",
          budgeted_spending: "3000.00", expected_income: "5000.00", currency: "USD"
        }
      }
    ])

    assert_raises(ActiveRecord::RecordInvalid) { Family::DataImporter.new(@family, ndjson).import! }
    assert_nil default_budget.reload.budgeted_spending
  end

  test "imports rules in their exported run order after existing rules" do
    existing = @family.rules.create!(resource_type: "transaction",
      actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
    rule_record = ->(name, position, stop_processing, apply_immediately) do
      {
        type: "Rule",
        version: 1,
        data: {
          name: name,
          resource_type: "transaction",
          active: true,
          position: position,
          stop_processing: stop_processing,
          apply_immediately: apply_immediately,
          conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
          actions: [ { action_type: "exclude_transaction" } ]
        }
      }
    end
    ndjson = build_ndjson([ rule_record.call("Second", 2, false, true), rule_record.call("First", 1, true, false) ])

    Family::DataImporter.new(@family, ndjson).import!

    assert_equal [ existing.id ] + @family.rules.where(name: %w[First Second]).in_order_of(:name, %w[First Second]).pluck(:id),
      @family.rules.ordered.pluck(:id).last(3)
    assert @family.rules.find_by(name: "First").stop_processing
    assert_not @family.rules.find_by(name: "Second").stop_processing
    assert_not @family.rules.find_by(name: "First").apply_immediately
    assert @family.rules.find_by(name: "Second").apply_immediately
  end

  test "imports rule groups by name and keeps each group in one block" do
    existing = @family.rule_groups.create!(name: "Food")
    rule_record = ->(name, position, group) do
      data = {
        name: name,
        resource_type: "transaction",
        active: true,
        position: position,
        conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
        actions: [ { action_type: "exclude_transaction" } ]
      }
      data[:group] = group unless group == :absent
      { type: "Rule", version: 1, data: data }
    end
    ndjson = build_ndjson([
      rule_record.call("Loose", 1, nil),
      rule_record.call("Groceries", 2, "Food"),
      rule_record.call("Restaurants", 3, "Food"),
      rule_record.call("Rent", 4, "Housing"),
      rule_record.call("Old export", 5, :absent)
    ])

    Family::DataImporter.new(@family, ndjson).import!

    rules = @family.rules.index_by(&:name)
    assert_nil rules["Loose"].rule_group
    assert_equal existing, rules["Groceries"].rule_group
    assert_equal existing, rules["Restaurants"].rule_group
    assert_equal "Housing", rules["Rent"].rule_group.name
    assert_nil rules["Old export"].rule_group
    # Rules joining a group that already exists run where that group stands.
    assert_equal [ "Groceries", "Restaurants", "Loose", "Rent", "Old export" ], @family.rules.ordered.pluck(:name).last(5)
  end

  test "session rule reimport keeps the run order of rules leaving a group" do
    group = @family.rule_groups.create!(name: "Food")
    build_rule = ->(name) do
      rule = @family.rules.build(name: name, resource_type: "transaction", active: true, rule_group: group)
      rule.conditions.build(condition_type: "transaction_name", operator: "like", value: name)
      rule.actions.build(action_type: "exclude_transaction")
      rule.tap(&:save!)
    end
    first = build_rule.call("First")
    second = build_rule.call("Second")
    build_rule.call("Staying")

    session = @family.import_sessions.create!(expected_chunks: 1)
    { "rule-1" => first, "rule-2" => second }.each do |source_id, rule|
      session.source_mappings.create!(family: @family, source_type: "Rule", source_id: source_id, target: rule)
    end
    rule_record = ->(id, name, position) do
      {
        type: "Rule",
        version: 1,
        data: {
          id: id,
          name: name,
          resource_type: "transaction",
          active: true,
          position: position,
          group: nil,
          conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
          actions: [ { action_type: "exclude_transaction" } ]
        }
      }
    end
    ndjson = build_ndjson([ rule_record.call("rule-1", "First", 1), rule_record.call("rule-2", "Second", 2) ])

    Family::DataImporter.new(@family, ndjson, import_session: session).import!

    assert_nil first.reload.rule_group
    assert_nil second.reload.rule_group
    assert_equal [ "Staying", "First", "Second" ], @family.rules.ordered.pluck(:name).last(3)
  end

  test "session rule reimport keeps the run order of rules leaving a group across chunks" do
    group = @family.rule_groups.create!(name: "Food")
    build_rule = ->(name) do
      rule = @family.rules.build(name: name, resource_type: "transaction", active: true, rule_group: group)
      rule.conditions.build(condition_type: "transaction_name", operator: "like", value: name)
      rule.actions.build(action_type: "exclude_transaction")
      rule.tap(&:save!)
    end
    first = build_rule.call("First")
    second = build_rule.call("Second")
    third = build_rule.call("Third")
    build_rule.call("Staying")

    session = @family.import_sessions.create!(expected_chunks: 2)
    { "rule-1" => first, "rule-2" => second, "rule-3" => third }.each do |source_id, rule|
      session.source_mappings.create!(family: @family, source_type: "Rule", source_id: source_id, target: rule)
    end
    rule_record = ->(id, name, position) do
      {
        type: "Rule",
        version: 1,
        data: {
          id: id,
          name: name,
          resource_type: "transaction",
          active: true,
          position: position,
          group: nil,
          conditions: [ { condition_type: "transaction_name", operator: "like", value: name } ],
          actions: [ { action_type: "exclude_transaction" } ]
        }
      }
    end

    Family::DataImporter.new(@family, build_ndjson([ rule_record.call("rule-1", "First", 1) ]), import_session: session).import!
    Family::DataImporter.new(
      @family,
      build_ndjson([ rule_record.call("rule-2", "Second", 2), rule_record.call("rule-3", "Third", 3) ]),
      import_session: session
    ).import!

    assert_nil first.reload.rule_group
    assert_nil second.reload.rule_group
    assert_nil third.reload.rule_group
    assert_equal [ "Staying", "First", "Second", "Third" ], @family.rules.ordered.pluck(:name).last(4)
  end

  test "imports rules with conditions and actions" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Categorize Coffee",
          resource_type: "transaction",
          active: true,
          conditions: [
            {
              condition_type: "transaction_name",
              operator: "like",
              value: "starbucks"
            }
          ],
          actions: [
            {
              action_type: "set_transaction_category",
              value: "Coffee"
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by(name: "Categorize Coffee")
    assert_not_nil rule
    assert rule.active
    assert_equal "transaction", rule.resource_type

    assert_equal 1, rule.conditions.count
    condition = rule.conditions.first
    assert_equal "transaction_name", condition.condition_type
    assert_equal "like", condition.operator
    assert_equal "starbucks", condition.value

    assert_equal 1, rule.actions.count
    action = rule.actions.first
    assert_equal "set_transaction_category", action.action_type

    # Category should be created
    category = @family.categories.find_by(name: "Coffee")
    assert_not_nil category
    assert_equal category.id, action.value
  end

  test "rejects a rule with an unknown resource type or action type" do
    [
      [ "account", "exclude_transaction" ],
      [ "transaction", "garbage" ]
    ].each do |resource_type, action_type|
      ndjson = build_ndjson([ {
        type: "Rule", version: 1,
        data: { id: "unknown-type-rule", name: "Unknown type", resource_type: resource_type,
                conditions: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ],
                actions: [ { action_type: action_type } ] }
      } ])

      error = assert_raises(ActiveRecord::RecordInvalid, action_type) do
        Family::DataImporter.new(@family, ndjson).import!
      end

      assert_match(/is not included in the list/, error.message)
      assert_nil @family.rules.find_by(name: "Unknown type")
    end
  end

  test "rejects invalid rule references before creating related records" do
    valid_condition = { condition_type: "transaction_name", operator: "like", value: "coffee" }
    cases = [
      [ { condition_type: "transaction_category", operator: "=", value: "Bad\0Category" },
        { action_type: "exclude_transaction" }, "value" ],
      [ valid_condition,
        { action_type: "set_transaction_merchant", value_ref: { name: "Bad\0Merchant" } }, "value_ref" ],
      [ valid_condition,
        { action_type: "set_transaction_tags", value_ref: [ { name: "Safe" }, { name: "Bad\0Tag" } ] }, "value_ref" ]
    ]
    counts = [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]

    cases.each do |condition, action, field|
      ndjson = build_ndjson([ {
        type: "Rule", version: 1,
        data: { name: "Invalid reference", resource_type: "transaction", conditions: [ condition ], actions: [ action ] }
      } ])

      error = assert_raises(Family::DataImporter::InvalidRecordError) do
        Family::DataImporter.new(@family, ndjson).import!
      end

      assert_equal "invalid_import_record", error.code
      assert_equal field, error.details[:field]
      assert_equal "(invalid text)", error.details[:value]
      assert_equal counts, [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]
    end
  end

  test "imports transaction_tag rule condition by remapping the tag name to an id" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Flag Reimbursable",
          resource_type: "transaction",
          active: true,
          conditions: [
            {
              condition_type: "transaction_tag",
              operator: "=",
              value: "Reimbursable"
            }
          ],
          actions: [
            {
              action_type: "set_transaction_name",
              value: "Reimbursable expense"
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by(name: "Flag Reimbursable")
    assert_not_nil rule

    condition = rule.conditions.first
    assert_equal "transaction_tag", condition.condition_type

    # The tag should be created and the condition value remapped to its id
    tag = @family.tags.find_by(name: "Reimbursable")
    assert_not_nil tag
    assert_equal tag.id, condition.value
  end

  test "reuses a category created for an earlier rule within the same import" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "First coffee rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "coffee" }
          ],
          actions: [
            { action_type: "set_transaction_category", value: "Coffee Shops" }
          ]
        }
      },
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Second coffee rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "latte" }
          ],
          actions: [
            { action_type: "set_transaction_category", value: "Coffee Shops" }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)

    assert_difference -> { @family.categories.where(name: "Coffee Shops").count }, 1 do
      importer.import!
    end

    category = @family.categories.find_by!(name: "Coffee Shops")
    first_rule = @family.rules.find_by!(name: "First coffee rule")
    second_rule = @family.rules.find_by!(name: "Second coffee rule")
    assert_equal category.id, first_rule.actions.first.value
    assert_equal category.id, second_rule.actions.first.value
  end

  test "points imported merchant rules at a reused provider merchant" do
    provider_merchant = ProviderMerchant.create!(name: "Synced Grocer", source: "plaid", provider_merchant_id: "plaid_synced_grocer")
    value_ref = { type: "Merchant", id: "old-provider-merchant", name: "Synced Grocer" }

    ndjson = build_ndjson([
      {
        type: "ProviderMerchant",
        data: { id: "old-provider-merchant", name: "Synced Grocer", source: "plaid", provider_merchant_id: "plaid_synced_grocer" }
      },
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Grocer rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_merchant", operator: "=", value: "Synced Grocer", value_ref: value_ref }
          ],
          actions: [
            { action_type: "set_transaction_merchant", value: "Synced Grocer", value_ref: value_ref }
          ]
        }
      }
    ])

    assert_no_difference -> { @family.merchants.count } do
      Family::DataImporter.new(@family, ndjson).import!
    end

    rule = @family.rules.find_by!(name: "Grocer rule")
    assert_equal provider_merchant.id, rule.conditions.first.value
    assert_equal provider_merchant.id, rule.actions.first.value
  end

  test "reuses a merchant created for an earlier rule within the same import" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "First coffee merchant rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "coffee" }
          ],
          actions: [
            { action_type: "set_transaction_merchant", value: "Blue Bottle" }
          ]
        }
      },
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Second coffee merchant rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "latte" }
          ],
          actions: [
            { action_type: "set_transaction_merchant", value: "Blue Bottle" }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)

    assert_difference -> { @family.merchants.where(name: "Blue Bottle").count }, 1 do
      importer.import!
    end

    merchant = @family.merchants.find_by!(name: "Blue Bottle")
    first_rule = @family.rules.find_by!(name: "First coffee merchant rule")
    second_rule = @family.rules.find_by!(name: "Second coffee merchant rule")
    assert_equal merchant.id, first_rule.actions.first.value
    assert_equal merchant.id, second_rule.actions.first.value
  end

  test "reuses a tag created for an earlier rule within the same import" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "First coffee tag rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "coffee" }
          ],
          actions: [
            { action_type: "set_transaction_tags", value: "Recurring" }
          ]
        }
      },
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Second coffee tag rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "latte" }
          ],
          actions: [
            { action_type: "set_transaction_tags", value: "Recurring" }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)

    assert_difference -> { @family.tags.where(name: "Recurring").count }, 1 do
      importer.import!
    end

    tag = @family.tags.find_by!(name: "Recurring")
    first_rule = @family.rules.find_by!(name: "First coffee tag rule")
    second_rule = @family.rules.find_by!(name: "Second coffee tag rule")
    assert_equal [ tag.id ], first_rule.actions.first.value.split(",")
    assert_equal [ tag.id ], second_rule.actions.first.value.split(",")
  end

  test "session rule reimport only replaces current family conditions and actions" do
    rule = @family.rules.build(name: "Original Rule", resource_type: "transaction", active: true)
    rule.conditions.build(condition_type: "transaction_name", operator: "like", value: "old")
    rule.actions.build(action_type: "auto_categorize")
    rule.save!

    other_family = Family.create!(name: "Other Rules Family", currency: "USD")
    other_rule = other_family.rules.build(name: "Other Rule", resource_type: "transaction", active: true)
    other_rule.conditions.build(condition_type: "transaction_name", operator: "like", value: "other-old")
    other_rule.actions.build(action_type: "auto_categorize")
    other_rule.save!

    other_session = other_family.import_sessions.create!(expected_chunks: 1)
    other_session.source_mappings.create!(
      family: other_family,
      source_type: "Rule",
      source_id: "rule-1",
      target: other_rule
    )

    session = @family.import_sessions.create!(expected_chunks: 1)
    session.source_mappings.create!(
      family: @family,
      source_type: "Rule",
      source_id: "rule-1",
      target: rule
    )

    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          id: "rule-1",
          name: "Updated Rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "new" }
          ],
          actions: [
            { action_type: "set_transaction_name", value: "Renamed" }
          ]
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson, import_session: session).import!

    assert_equal [ "new" ], rule.reload.conditions.map(&:value)
    assert_equal [ "set_transaction_name" ], rule.actions.map(&:action_type)
    assert_equal [ "other-old" ], other_rule.reload.conditions.map(&:value)
    assert_equal [ "auto_categorize" ], other_rule.actions.map(&:action_type)
  end

  test "session rule reimport keeps apply immediately when the export predates it" do
    rule = @family.rules.create!(name: "Immediate Rule", resource_type: "transaction", active: true, apply_immediately: true,
      actions: [ Rule::Action.new(action_type: "exclude_transaction") ])
    session = @family.import_sessions.create!(expected_chunks: 1)
    session.source_mappings.create!(family: @family, source_type: "Rule", source_id: "rule-1", target: rule)

    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          id: "rule-1",
          name: "Immediate Rule",
          resource_type: "transaction",
          active: true,
          actions: [ { action_type: "exclude_transaction" } ]
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson, import_session: session).import!

    assert rule.reload.apply_immediately
  end

  test "imports rules from normalized operand value refs" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Map Merchant To Dining",
          resource_type: "transaction",
          active: true,
          conditions: [
            {
              condition_type: "transaction_merchant",
              operator: "=",
              value_ref: {
                type: "Merchant",
                id: "source-merchant-id",
                name: "Coffee Bar"
              }
            }
          ],
          actions: [
            {
              action_type: "set_transaction_category",
              value_ref: {
                type: "Category",
                id: "source-category-id",
                name: "Dining"
              }
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by!(name: "Map Merchant To Dining")
    merchant = @family.merchants.find_by!(name: "Coffee Bar")
    category = @family.categories.find_by!(name: "Dining")

    assert_equal merchant.id, rule.conditions.first.value
    assert_equal category.id, rule.actions.first.value
  end

  test "imports rule value refs when legacy operand values are stale UUIDs" do
    stale_merchant_id = SecureRandom.uuid
    stale_category_id = SecureRandom.uuid
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Map Stale UUID Operands",
          resource_type: "transaction",
          active: true,
          conditions: [
            {
              condition_type: "transaction_merchant",
              operator: "=",
              value: stale_merchant_id,
              value_ref: {
                type: "Merchant",
                id: stale_merchant_id,
                name: "Coffee Bar"
              }
            }
          ],
          actions: [
            {
              action_type: "set_transaction_category",
              value: stale_category_id,
              value_ref: {
                type: "Category",
                id: stale_category_id,
                name: "Dining"
              }
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by!(name: "Map Stale UUID Operands")
    merchant = @family.merchants.find_by!(name: "Coffee Bar")
    category = @family.categories.find_by!(name: "Dining")

    assert_equal merchant.id, rule.conditions.first.value
    assert_equal category.id, rule.actions.first.value
    assert_not @family.merchants.exists?(name: stale_merchant_id)
    assert_not @family.categories.exists?(name: stale_category_id)
  end

  test "imports a multi-tag rule action by resolving each tag id ref independently" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Tag As Weekly And Recurring",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "subscription" }
          ],
          actions: [
            {
              action_type: "set_transaction_tags",
              value: "Weekly,Recurring",
              value_ref: [
                { "type" => "Tag", "id" => "source-tag-1", "name" => "Weekly" },
                { "type" => "Tag", "id" => "source-tag-2", "name" => "Recurring" }
              ]
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by!(name: "Tag As Weekly And Recurring")
    weekly_tag = @family.tags.find_by!(name: "Weekly")
    recurring_tag = @family.tags.find_by!(name: "Recurring")

    imported_tag_ids = rule.actions.first.value.split(",")
    assert_equal [ weekly_tag.id, recurring_tag.id ].sort, imported_tag_ids.sort
    # Regression guard: must not create one bogus tag literally named "Weekly,Recurring"
    assert_not @family.tags.exists?(name: "Weekly,Recurring")
    assert_equal 2, @family.tags.count
  end

  test "imports a multi-tag rule action with a comma-containing tag name from CSV-quoted value" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Comma Tag Name Rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "subscription" }
          ],
          actions: [
            {
              action_type: "set_transaction_tags",
              value: "Weekly,\"Food, Dining\""
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by!(name: "Comma Tag Name Rule")
    weekly_tag = @family.tags.find_by!(name: "Weekly")
    comma_tag = @family.tags.find_by!(name: "Food, Dining")

    imported_tag_ids = rule.actions.first.value.split(",")
    assert_equal [ weekly_tag.id, comma_tag.id ].sort, imported_tag_ids.sort
    assert_equal 2, @family.tags.count
  end

  test "imports a multi-tag rule action from a legacy single-tag value_ref hash" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Legacy Single Tag Action",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "subscription" }
          ],
          actions: [
            {
              action_type: "set_transaction_tags",
              value: "Weekly",
              value_ref: { "type" => "Tag", "id" => "source-tag-1", "name" => "Weekly" }
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by!(name: "Legacy Single Tag Action")
    weekly_tag = @family.tags.find_by!(name: "Weekly")

    assert_equal weekly_tag.id, rule.actions.first.value
  end

  test "rejects a split rule action with invalid text before creating related records" do
    counts = [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]

    [ { name: "Bad\0Name" }, { category: "Bad\0Category" }, { merchant: "Bad\0Merchant" }, { tags: [ "Safe", "Bad\0Tag" ] } ].each do |bad|
      ndjson = build_ndjson([ {
        type: "Rule", version: 1,
        data: {
          name: "Invalid split", resource_type: "transaction",
          conditions: [ { condition_type: "transaction_name", operator: "like", value: "rent" } ],
          actions: [ {
            action_type: "split_transaction",
            value: { splits: [
              { type: "percentage", name: "A", share: "50" }.merge(bad),
              { type: "percentage", name: "B", share: "50" }
            ] }.to_json
          } ]
        }
      } ])

      error = assert_raises(Family::DataImporter::InvalidRecordError, bad.inspect) do
        Family::DataImporter.new(@family, ndjson).import!
      end

      assert_equal "value", error.details[:field]
      assert_equal counts, [ @family.rules.count, @family.categories.count, @family.merchants.count, @family.tags.count ]
    end
  end

  test "imports a split rule action whose rows carry foreign ids by dropping them" do
    foreign_category = categories(:food_and_drink)
    own_tag = @family.tags.create!(name: "Shared")

    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Split With Foreign Ids",
          resource_type: "transaction",
          active: true,
          conditions: [ { condition_type: "transaction_name", operator: "like", value: "rent" } ],
          actions: [
            {
              action_type: "split_transaction",
              value: {
                splits: [
                  { type: "percentage", name: "A", share: "50", category_id: foreign_category.id, tag_ids: [ own_tag.id, SecureRandom.uuid ] },
                  { type: "percentage", name: "B", share: "50", category: "Housing" }
                ]
              }.to_json
            }
          ]
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    first, second = JSON.parse(@family.rules.find_by!(name: "Split With Foreign Ids").actions.sole.value)["splits"]
    assert_nil first["category_id"]
    assert_equal [ own_tag.id ], first["tag_ids"]
    assert_equal @family.categories.find_by!(name: "Housing").id, second["category_id"]
  end

  test "remaps raw split ids from an older export through the imported records" do
    ndjson = build_ndjson([
      { type: "Category", data: { id: "source-category", name: "Groceries", color: "#407706" } },
      { type: "Tag", data: { id: "source-tag", name: "Shared", color: "#00FF00" } },
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Raw Id Split",
          resource_type: "transaction",
          active: true,
          conditions: [ { condition_type: "transaction_name", operator: "like", value: "market" } ],
          actions: [
            {
              action_type: "split_transaction",
              value: {
                splits: [
                  { type: "percentage", name: "A", share: "50", category_id: "source-category", tag_ids: [ "source-tag" ] },
                  { type: "percentage", name: "B", share: "50" }
                ]
              }.to_json
            }
          ]
        }
      }
    ])

    Family::DataImporter.new(@family, ndjson).import!

    first = JSON.parse(@family.rules.find_by!(name: "Raw Id Split").actions.sole.value)["splits"].first
    assert_equal @family.categories.find_by!(name: "Groceries").id, first["category_id"]
    assert_equal [ @family.tags.find_by!(name: "Shared").id ], first["tag_ids"]
  end

  test "rejects a non-string split value with a validation error" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Scalar Split",
          resource_type: "transaction",
          active: true,
          conditions: [ { condition_type: "transaction_name", operator: "like", value: "x" } ],
          actions: [ { action_type: "split_transaction", value: 5 } ]
        }
      }
    ])

    assert_raises(ActiveRecord::RecordInvalid) do
      Family::DataImporter.new(@family, ndjson).import!
    end
  end

  test "preserves explicit false rule operand values" do
    importer = Family::DataImporter.new(@family, "")

    value = importer.send(
      :rule_operand_value,
      {
        "value" => false,
        "value_ref" => {
          "type" => "Category",
          "name" => "Fallback"
        }
      }
    )

    assert_equal false, value
  end

  test "imports rules with compound conditions" do
    ndjson = build_ndjson([
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Compound Rule",
          resource_type: "transaction",
          active: true,
          conditions: [
            {
              condition_type: "compound",
              operator: "or",
              sub_conditions: [
                {
                  condition_type: "transaction_name",
                  operator: "like",
                  value: "walmart"
                },
                {
                  condition_type: "transaction_name",
                  operator: "like",
                  value: "target"
                }
              ]
            }
          ],
          actions: [
            {
              action_type: "auto_categorize"
            }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    importer.import!

    rule = @family.rules.find_by(name: "Compound Rule")
    assert_not_nil rule

    parent_condition = rule.conditions.first
    assert_equal "compound", parent_condition.condition_type
    assert_equal "or", parent_condition.operator
    assert_equal 2, parent_condition.sub_conditions.count
  end

  test "skips invalid records gracefully" do
    ndjson = "not valid json\n" + build_ndjson([
      {
        type: "Account",
        data: {
          id: "valid-acct",
          name: "Valid Account",
          balance: "1000",
          currency: "USD",
          accountable_type: "Depository"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    assert_equal 1, result[:account_ids].count
    account_id = result[:account_ids].first
    assert_equal "Valid Account", Account.find(account_id).name
  end

  test "session import persists source mappings without retaining them on the session" do
    session = @family.import_sessions.create!(expected_chunks: 1)
    ndjson = [
      { type: "Account", data: {
        id: "acct-1", name: "Mapped Account", balance: "100.00", currency: "USD",
        accountable_type: "Depository", accountable: { subtype: "checking" }
      } },
      { type: "Transaction", data: {
        id: "txn-1", account_id: "acct-1", date: "2024-01-15", amount: "-25.00",
        name: "Coffee", currency: "USD"
      } }
    ].map(&:to_json).join("\n")

    Family::DataImporter.new(@family, ndjson, import_session: session).import!

    # The session lives for every chunk of a publish run; anything built onto
    # its association stays in memory until the whole run ends.
    assert_empty session.source_mappings.target
    assert_empty @family.import_source_mappings.target
    assert_equal %w[Account Transaction], ImportSourceMapping.where(import_session_id: session.id).pluck(:source_type).sort
  end

  test "skips unsupported record types" do
    ndjson = build_ndjson([
      {
        type: "UnsupportedType",
        data: { id: "unknown" }
      },
      {
        type: "Account",
        data: {
          id: "valid-acct",
          name: "Known Account",
          balance: "1000",
          currency: "USD",
          accountable_type: "Depository"
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    assert_equal 1, result[:account_ids].count
  end

  test "full import scenario with all entity types" do
    ndjson = build_ndjson([
      # Account
      {
        type: "Account",
        data: {
          id: "acct-main",
          name: "Main Checking",
          balance: "5000",
          currency: "USD",
          accountable_type: "Depository"
        }
      },
      # Category
      {
        type: "Category",
        data: {
          id: "cat-food",
          name: "Food",
          color: "#FF5733",
          classification: "expense"
        }
      },
      # Tag
      {
        type: "Tag",
        data: {
          id: "tag-weekly",
          name: "Weekly"
        }
      },
      # Merchant
      {
        type: "Merchant",
        data: {
          id: "merchant-1",
          name: "Local Grocery"
        }
      },
      # Transaction
      {
        type: "RecurringTransaction",
        data: {
          id: "recurring-grocery",
          account_id: "acct-main",
          merchant_id: "merchant-1",
          amount: "-75.50",
          currency: "USD",
          expected_day_of_month: 15,
          last_occurrence_date: "2024-01-15",
          next_expected_date: "2024-02-15",
          status: "active",
          occurrence_count: 3,
          manual: false
        }
      },
      # Transaction
      {
        type: "Transaction",
        data: {
          id: "txn-1",
          account_id: "acct-main",
          date: "2024-01-15",
          amount: "-75.50",
          name: "Weekly groceries",
          currency: "USD",
          category_id: "cat-food",
          merchant_id: "merchant-1",
          tag_ids: [ "tag-weekly" ]
        }
      },
      # Budget
      {
        type: "Budget",
        data: {
          id: "budget-jan",
          start_date: "2024-01-01",
          end_date: "2024-01-31",
          budgeted_spending: "2000",
          expected_income: "4000",
          currency: "USD"
        }
      },
      # BudgetCategory
      {
        type: "BudgetCategory",
        data: {
          id: "bc-food",
          budget_id: "budget-jan",
          category_id: "cat-food",
          budgeted_spending: "500",
          currency: "USD"
        }
      },
      # Rule
      {
        type: "Rule",
        version: 1,
        data: {
          name: "Auto-tag groceries",
          resource_type: "transaction",
          active: true,
          conditions: [
            { condition_type: "transaction_name", operator: "like", value: "grocery" }
          ],
          actions: [
            { action_type: "set_transaction_tags", value: "Weekly" }
          ]
        }
      }
    ])

    importer = Family::DataImporter.new(@family, ndjson)
    result = importer.import!

    # Verify all entities were created
    assert_equal 1, result[:account_ids].count
    assert_equal 1, @family.categories.count
    assert_equal 1, @family.tags.count
    assert_equal 1, @family.merchants.count
    assert_equal 1, @family.recurring_transactions.count
    assert_equal 1, @family.transactions.count
    assert_equal 1, @family.budgets.count
    assert_equal 1, @family.budget_categories.count
    assert_equal 1, @family.rules.count

    # Verify relationships
    transaction = @family.transactions.first
    assert_equal "Food", transaction.category.name
    assert_equal "Local Grocery", transaction.merchant.name
    assert_equal "Weekly", transaction.tags.first.name

    recurring_transaction = @family.recurring_transactions.first
    assert_equal "Main Checking", recurring_transaction.account.name
    assert_equal "Local Grocery", recurring_transaction.merchant.name
  end

  # Everything below the series was silently absent from an export: a restored
  # bill kept its name and amount and lost its cadence, its payment history and
  # every setting that decides how it behaves.
  test "imports the bills subsystem, reattaching payments to their transactions" do
    importer = Family::DataImporter.new(@family, build_ndjson(bills_ndjson_records))
    importer.import!

    series = @family.recurring_transactions.sole
    assert_equal "bill", series.bill_type
    assert_equal 9.5, series.amount_tolerance_pct.to_f
    assert_equal "before", series.weekend_adjust
    assert_equal "2000", series.dedup_scope
    assert_equal [ "WATSON PROPERTY" ], series.matcher_hints["name_aliases"]

    rule = series.recurrence_rules.sole
    assert_equal "weekly", rule.frequency, "cadence must survive, not fall back to monthly"
    assert_equal 2, rule.interval

    occurrence = series.recurring_occurrences.find_by(original_due_on: Date.new(2026, 6, 9))
    assert occurrence.paid?
    assert_equal 2000, occurrence.expected_amount.to_f

    allocation = occurrence.allocations.sole
    assert_equal 2000, allocation.allocated_amount.to_f
    assert_equal "user_confirmed", allocation.source
    assert_not_nil allocation.entry, "the payment must reattach to the imported transaction"
    assert_equal 2000, allocation.entry.amount.to_f
    assert_equal Date.new(2026, 6, 9), allocation.entry.date
  end

  test "replaying a bills export changes nothing the second time" do
    records = bills_ndjson_records
    session = @family.import_sessions.create!
    Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!

    census = -> {
      [ RecurrenceRule.joins(:recurring_transaction).where(recurring_transactions: { family_id: @family.id }).count,
        RecurringOccurrence.where(family_id: @family.id).count,
        RecurringAllocation.joins(:recurring_occurrence).where(recurring_occurrences: { family_id: @family.id }).count ]
    }
    before = census.call

    # The replay contract is the session's: mappings persisted on the first
    # pass, so a fresh importer resolves every record to the row already
    # created instead of skipping or duplicating it.
    Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!

    assert_equal before, census.call
  end

  test "a closed occurrence exported without closed_at replays to the same timestamp" do
    records = bills_ndjson_records
    records.each { |record| record[:data].delete(:closed_at) if record[:type] == "RecurringOccurrence" }

    session = @family.import_sessions.create!
    Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!
    occurrence = @family.recurring_transactions.sole
                        .recurring_occurrences.find_by!(original_due_on: Date.new(2026, 6, 9))
    first_stamp = occurrence.closed_at
    assert_not_nil first_stamp
    assert_equal Date.new(2026, 6, 9), first_stamp.to_date, "the stand-in derives from the due date"

    # A day later so a stand-in recomputed at import time would visibly move.
    travel 1.day do
      Family::DataImporter.new(@family, build_ndjson(records), import_session: session).import!
    end

    assert_equal first_stamp, occurrence.reload.closed_at,
      "an import-time stand-in would move the historical timestamp on every replay"
  end

  test "one incoherent recurrence rule row is skipped, not the whole import" do
    records = bills_ndjson_records
    records.each do |record|
      record[:data][:interval] = nil if record[:type] == "RecurrenceRule"
    end

    result = Family::DataImporter.new(@family, build_ndjson(records)).import!

    assert_equal 1, result.dig(:summary, "recurrence_rules", "skipped")
    assert_equal 1, @family.recurring_transactions.count,
      "the rest of the file must land even though one rule row was stale"
  end

  test "a hand-recorded allocation without a paid_on is skipped, not defaulted to today" do
    records = bills_ndjson_records
    records.each do |record|
      next unless record[:type] == "RecurringAllocation"

      record[:data].delete(:transaction_id)
      record[:data].delete(:paid_on)
    end

    result = Family::DataImporter.new(@family, build_ndjson(records)).import!

    occurrence = @family.recurring_transactions.sole
                        .recurring_occurrences.find_by!(original_due_on: Date.new(2026, 6, 9))
    assert_equal 0, occurrence.allocations.count,
      "a defaulted paid_on would make every later replay insert a fresh copy"
    assert_equal 1, result.dig(:summary, "recurring_allocations", "skipped")
  end

  test "recurring records whose series never came across are counted as skipped" do
    ndjson = build_ndjson([
      { type: "RecurringPriceChange", data: {
          id: "old-change", recurring_transaction_id: "missing-series",
          effective_on: "2026-05-01", previous_amount: "10.0", new_amount: "12.0",
          currency: "USD" } }
    ])

    result = Family::DataImporter.new(@family, ndjson).import!

    assert_equal 1, result.dig(:summary, "recurring_price_changes", "skipped")
  end

  # A bill created with a full payment history must not also carry the
  # occurrences its own creation callback generates.
  test "imported occurrences do not duplicate the ones a new series generates" do
    Family::DataImporter.new(@family, build_ndjson(bills_ndjson_records)).import!

    series = @family.recurring_transactions.sole
    duplicates = series.recurring_occurrences.group(:original_due_on).count.select { |_, n| n > 1 }

    assert_empty duplicates, "generation and import collided on the same due date"
  end


  # Occurrence generation fires after_commit on the instance the importer
  # created. If validation cached its rules while they were still empty, a
  # biweekly restore would materialize monthly phantom occurrences beside the
  # real schedule.
  test "a restored biweekly series keeps its cadence, with no monthly phantoms" do
    Family::DataImporter.new(@family, build_ndjson(bills_ndjson_records)).import!

    series = @family.recurring_transactions.find_by!(name: "Rent")

    # The imported historical row is weekend-adjusted off its weekday, so the
    # cadence check runs on what generation produced: every scheduled cycle
    # lands on the rule's weekday, fourteen days from its neighbour. A monthly
    # phantom would land on the 9th, whatever weekday that is.
    generated = series.recurring_occurrences.open_status.order(:due_on).pluck(:due_on)
    assert generated.any?, "generation must have materialized future cycles"

    generated.each do |due_on|
      assert_equal 1, due_on.cwday, "#{due_on} is not the rule's Monday"
    end
    generated.each_cons(2) do |a, b|
      assert_equal 14, (b - a).to_i, "#{a} to #{b} is not one biweekly step"
    end
  end

  # Session imports arrive in chunks, each processed by a fresh importer. The
  # occurrence map used to live in memory, so an allocation whose occurrence
  # landed in an earlier chunk was silently skipped.
  test "an allocation in a later session chunk finds its occurrence from an earlier one" do
    records = bills_ndjson_records
    allocations = records.select { |r| r[:type] == "RecurringAllocation" }
    rest = records - allocations
    assert allocations.any?, "fixture must carry at least one allocation"

    session = @family.import_sessions.create!(expected_chunks: 2)
    session.attach_chunk!(sequence: 1, client_chunk_id: "bills",
                          content: build_ndjson(rest),
                          filename: "bills.ndjson", content_type: "application/x-ndjson")
    session.attach_chunk!(sequence: 2, client_chunk_id: "allocations",
                          content: build_ndjson(allocations),
                          filename: "allocations.ndjson", content_type: "application/x-ndjson")

    session.publish

    series = @family.recurring_transactions.find_by!(name: "Rent")
    assert_operator RecurringAllocation.joins(:recurring_occurrence)
      .where(recurring_occurrences: { recurring_transaction_id: series.id }).count, :>, 0,
      "the later chunk's allocation must resolve its occurrence through the persisted mapping"
  end

  private

    # A FIFO account's export: 60 bought at $12 with the user's cost of $600,
    # 40 at $20, and a sale of 10 that names the $20 lot.
    def lot_export(switch_to: nil)
      source = Family.create!(name: "Lot Source", currency: "USD", locale: "en", date_format: "%Y-%m-%d")
      account = source.accounts.create!(name: "Lot Round Trip", accountable: Investment.new, balance: 0, cash_balance: 0, currency: "USD")
      account.update!(cost_basis_method: "fifo")
      security = Security.create!(ticker: "LRT#{SecureRandom.hex(3).upcase}", name: "Lot Round Trip")
      Security::Price.insert_all((3.days.ago.to_date..Date.current).map { |date| { security_id: security.id, date: date, price: 30, currency: "USD" } })
      first_buy = create_trade(security, account: account, qty: 60, price: 12, date: 3.days.ago.to_date)
      second_buy = create_trade(security, account: account, qty: 40, price: 20, date: 2.days.ago.to_date)
      # Sold on the day the named lot was bought, which a sale may do.
      sale = create_trade(security, account: account, qty: -10, price: 25, date: 2.days.ago.to_date)
      sale.trade.update!(lot_source_entry: second_buy)
      # The sale gets the lowest trade id, so an export ordered by date and id
      # alone would write it ahead of the lot it names, bought the same day.
      low_id = "00000000-0000-4000-8000-#{SecureRandom.hex(6)}"
      Trade.where(id: sale.entryable_id).update_all(id: low_id)
      sale.update_columns(entryable_id: low_id)
      Holding::Materializer.new(account.reload, strategy: :forward).materialize_holdings
      HoldingLot.find_by!(source_entry: first_buy).set_manual_total_cost!(600)
      account.update!(cost_basis_method: switch_to) if switch_to

      ndjson = nil
      Zip::File.open_buffer(Family::DataExporter.new(source).generate_export) { |zip| ndjson = zip.read("all.ndjson") }
      ndjson
    end

    # Exports a one-day run of trades entered in the given order, imports it
    # into a fresh family, and returns the imported position's cost basis.
    def round_trip_cost_basis(method, trades)
      source = Family.create!(name: "Order Source", currency: "USD", locale: "en", date_format: "%Y-%m-%d")
      account = source.accounts.create!(name: "Order Round Trip", accountable: Investment.new, balance: 0, cash_balance: 0, currency: "USD")
      account.update!(cost_basis_method: method)
      security = Security.create!(ticker: "ORT#{SecureRandom.hex(3).upcase}", name: "Order Round Trip")
      day = 2.days.ago.to_date
      Security::Price.insert_all((day..Date.current).map { |date| { security_id: security.id, date: date, price: 30, currency: "USD" } })
      trades.each_with_index do |(qty, price), index|
        create_trade(security, account: account, qty: qty, price: price, date: day)
          .update_columns(created_at: 1.hour.ago + index.minutes)
      end

      ndjson = nil
      Zip::File.open_buffer(Family::DataExporter.new(source).generate_export) { |zip| ndjson = zip.read("all.ndjson") }
      target = Family.create!(name: "Order Target", currency: "USD", locale: "en", date_format: "%Y-%m-%d")
      Family::DataImporter.new(target, ndjson).import!

      imported = target.accounts.find_by!(name: "Order Round Trip")
      Holding::Materializer.new(imported, strategy: :forward).materialize_holdings
      imported.holdings.where(date: day).sole.cost_basis
    end

    def edit_trades(ndjson)
      ndjson.split("\n").map { |line| JSON.parse(line) }.each { |record| yield record["data"] if record["type"] == "Trade" }.map(&:to_json).join("\n")
    end

    def lot_trades(account)
      account.entries.where(entryable_type: "Trade").includes(:entryable).index_by { |entry| entry.trade.qty.to_i }
    end

    def build_ndjson(records)
      records.map(&:to_json).join("\n")
    end

    def full_export_ndjson(family)
      ndjson = nil
      Zip::File.open_buffer(Family::DataExporter.new(family).generate_export) { |zip| ndjson = zip.read("all.ndjson") }
      ndjson
    end

    # A bill, one non-monthly rule, a settled occurrence, and the payment that
    # settled it, pointing at a transaction arriving in the same export.
    def bills_ndjson_records
      [
        { type: "Account", data: {
            id: "old-acct", name: "Checking", balance: "0", currency: "USD",
            accountable_type: "Depository", accountable: { subtype: "checking" } } },
        { type: "RecurringTransaction", data: {
            id: "old-series", account_id: "old-acct", amount: "2000.0", currency: "USD",
            expected_day_of_month: 9, last_occurrence_date: "2026-06-09",
            next_expected_date: "2026-07-09", status: "active", name: "Rent",
            manual: true, bill_type: "bill", amount_tolerance_pct: "9.5",
            anchor_date: "2026-06-09", weekend_adjust: "before", dedup_scope: "2000",
            matcher_hints: { "name_aliases" => [ "WATSON PROPERTY" ] } } },
        { type: "RecurrenceRule", data: {
            id: "old-rule", recurring_transaction_id: "old-series",
            frequency: "weekly", interval: 2, weekday: 1, position: 0 } },
        { type: "Transaction", data: {
            id: "old-txn", entry_id: "old-entry", account_id: "old-acct",
            date: "2026-06-09", amount: "2000.0", currency: "USD", name: "Rent payment" } },
        { type: "RecurringOccurrence", data: {
            id: "old-occ", recurring_transaction_id: "old-series",
            original_due_on: "2026-06-09", due_on: "2026-06-09", currency: "USD",
            expected_amount: "2000.0", status: "paid",
            closed_at: "2026-06-09T12:00:00Z", closed_source: "auto" } },
        { type: "RecurringAllocation", data: {
            id: "old-alloc", recurring_occurrence_id: "old-occ", transaction_id: "old-txn",
            allocated_amount: "2000.0", currency: "USD", state: "confirmed",
            source: "user_confirmed", paid_on: "2026-06-09" } }
      ]
    end
end