Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
69.8 KB
Raw Blame
require "test_helper"

class Family::DataExporterTest < ActiveSupport::TestCase
  setup do
    @family = families(:dylan_family)
    @other_family = families(:empty)
    @exporter = Family::DataExporter.new(@family)
    @opening_anchor_date = Date.parse("2024-05-01")

    # Create some test data for the family
    @account = @family.accounts.create!(
      name: "Test Account",
      accountable: Depository.new,
      balance: 1000,
      currency: "USD"
    )
    @account.entries.create!(
      date: @opening_anchor_date,
      amount: 1000,
      name: "Opening balance",
      currency: "USD",
      entryable: Valuation.new(kind: "opening_anchor")
    )

    @category = @family.categories.create!(
      name: "Test Category",
      color: "#FF0000"
    )

    @tag = @family.tags.create!(
      name: "Test Tag",
      color: "#00FF00"
    )

    @rule = @family.rules.build(
      name: "Test Rule",
      resource_type: "transaction",
      active: true
    )
    @rule.conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "test"
    )
    @rule.actions.build(
      action_type: "set_transaction_category",
      value: @category.id
    )
    @rule.save!
  end

  test "generates a zip file with all required files" do
    zip_data = @exporter.generate_export

    assert zip_data.is_a?(StringIO)

    # Check that the zip contains all expected files
    expected_files = [ "version.txt", "accounts.csv", "transactions.csv", "trades.csv", "categories.csv", "merchants.csv", "rules.csv", "attachments.json", "all.ndjson" ]

    Zip::File.open_buffer(zip_data) do |zip|
      actual_files = zip.entries.map(&:name)
      assert_equal expected_files.sort, actual_files.sort
    end
  end

  test "exports attachment manifest metadata without binary payloads" do
    entry = @account.entries.create!(
      name: "Receipt Transaction",
      amount: 12.34,
      currency: "USD",
      date: Date.current,
      entryable: Transaction.new
    )
    transaction = entry.transaction
    transaction.attachments.attach(
      io: StringIO.new("receipt bytes"),
      filename: "receipt.pdf",
      content_type: "application/pdf"
    )

    family_document = @family.family_documents.create!(
      filename: "statement.pdf",
      status: "ready"
    )
    family_document.file.attach(
      io: StringIO.new("statement bytes"),
      filename: "statement.pdf",
      content_type: "application/pdf"
    )

    other_account = @other_family.accounts.create!(
      name: "Other Attachment Account",
      accountable: Depository.new,
      balance: 0,
      currency: "USD"
    )
    other_entry = other_account.entries.create!(
      name: "Other Receipt",
      amount: 1,
      currency: "USD",
      date: Date.current,
      entryable: Transaction.new
    )
    other_entry.transaction.attachments.attach(
      io: StringIO.new("other bytes"),
      filename: "other-receipt.pdf",
      content_type: "application/pdf"
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      manifest = JSON.parse(zip.read("attachments.json"))
      attachments = manifest["attachments"]
      filenames = attachments.map { |attachment| attachment["filename"] }

      assert_equal 1, manifest["version"]
      assert_equal false, manifest["binary_included"]
      assert_includes filenames, "receipt.pdf"
      assert_includes filenames, "statement.pdf"
      refute_includes filenames, "other-receipt.pdf"

      transaction_item = attachments.find { |attachment| attachment["record_type"] == "Transaction" }
      assert_equal transaction.id, transaction_item["record_id"]
      assert_equal entry.id, transaction_item["entry_id"]
      assert_equal @account.id, transaction_item["account_id"]
      assert_equal "attachments", transaction_item["name"]
      assert_equal "application/pdf", transaction_item["content_type"]
      assert_equal false, transaction_item["binary_included"]

      document_item = attachments.find { |attachment| attachment["record_type"] == "FamilyDocument" }
      assert_equal family_document.id, document_item["record_id"]
      assert_equal "ready", document_item["status"]
      assert_equal "file", document_item["name"]
      assert_equal false, document_item["binary_included"]
    end
  end

  test "exports split parent receipts in attachment manifest" do
    split_parent = create_transaction_entry(
      @account,
      amount: 60,
      date: Date.parse("2024-01-25"),
      name: "Split parent receipt"
    )
    split_parent.entryable.attachments.attach(
      io: StringIO.new("split parent receipt bytes"),
      filename: "split-parent-receipt.pdf",
      content_type: "application/pdf"
    )
    split_parent.split!([
      { name: "Split child", amount: 60, category_id: @category.id }
    ])

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      manifest = JSON.parse(zip.read("attachments.json"))
      attachment = manifest["attachments"].find { |item| item["filename"] == "split-parent-receipt.pdf" }

      assert attachment
      assert_equal "Transaction", attachment["record_type"]
      assert_equal split_parent.entryable.id, attachment["record_id"]
      assert_equal split_parent.id, attachment["entry_id"]
      assert_equal @account.id, attachment["account_id"]
    end
  end

  test "generates valid CSV files" do
    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      # Check accounts.csv
      accounts_csv = zip.read("accounts.csv")
      assert_equal [ "id", "name", "type", "subtype", "balance", "currency", "created_at" ],
                   CSV.parse(accounts_csv, headers: true).headers

      # Check version marker
      version_txt = zip.read("version.txt")
      assert_includes version_txt, "export_version: 2"
      refute_includes version_txt, "csv_export_version"

      # Check transactions.csv
      transactions_csv = zip.read("transactions.csv")
      assert_equal [ "date", "account_name", "amount", "name", "category", "tags", "notes", "currency" ],
                   CSV.parse(transactions_csv, headers: true).headers

      # Check trades.csv
      trades_csv = zip.read("trades.csv")
      assert_equal [ "date", "account_name", "ticker", "quantity", "price", "amount", "currency" ],
                   CSV.parse(trades_csv, headers: true).headers

      # Check categories.csv
      categories_csv = zip.read("categories.csv")
      assert categories_csv.include?(%q("name","color","parent_category","lucide_icon"))

      # Check merchants.csv
      merchants_csv = zip.read("merchants.csv")
      assert merchants_csv.include?(%q("name","color","website_url"))

      # Check rules.csv
      rules_csv = zip.read("rules.csv")
      assert rules_csv.include?(%q("name","resource_type","active","effective_date","conditions","actions","group"))
    end
  end

  test "exports merchants in CSV format scoped to the family" do
    merchant = @family.merchants.create!(name: "Coffee Shop", website_url: "https://coffeeshop.com")
    other_merchant = @other_family.merchants.create!(name: "Other Family Store")

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      rows = CSV.parse(zip.read("merchants.csv"), headers: true)
      row = rows.find { |csv_row| csv_row["name"] == merchant.name }

      assert_not_nil row
      assert_equal merchant.color, row["color"]
      assert_equal merchant.website_url, row["website_url"]
      refute rows.any? { |csv_row| csv_row["name"] == other_merchant.name }
    end
  end

  test "exported merchants CSV round-trips through MerchantImport" do
    merchant = @family.merchants.create!(name: "Pizza Palace", website_url: "https://pizzapalace.com")

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      import = @other_family.imports.create!(
        type: "MerchantImport",
        raw_file_str: zip.read("merchants.csv"),
        col_sep: ","
      )
      import.generate_rows_from_csv
      row = import.rows.reload.find_by!(name: "Pizza Palace")

      assert_equal merchant.color, row.merchant_color
      assert_equal "https://pizzapalace.com", row.merchant_website

      # The export carries every family merchant (incl. fixtures), so scope the
      # count assertion to the merchant under test.
      assert_difference -> { @other_family.merchants.where(name: "Pizza Palace").count }, 1 do
        import.send(:import!)
      end

      imported = @other_family.merchants.find_by!(name: "Pizza Palace")
      assert_equal merchant.color, imported.color
      assert_equal "https://pizzapalace.com", imported.website_url
    end
  end

  test "exports transaction CSV rows with restored legacy ISO date stored amount account name and comma tags" do
    tag2 = @family.tags.create!(name: "Food, Dining|Cafe", color: "#0000FF")
    entry = @account.entries.create!(
      name: "CSV Grocery",
      amount: 42.50,
      currency: "USD",
      date: Date.parse("2024-05-15"),
      notes: "Weekly grocery run",
      entryable: Transaction.new(category: @category)
    )
    entry.transaction.tags << @tag
    entry.transaction.tags << tag2

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      rows = CSV.parse(zip.read("transactions.csv"), headers: true)
      row = rows.find { |csv_row| csv_row["name"] == "CSV Grocery" }

      assert_not_nil row
      assert_equal "2024-05-15", row["date"]
      assert_equal "42.5", row["amount"]
      assert_equal @account.name, row["account_name"]
      assert_includes row["tags"], ","
      assert_includes row["tags"], "\\,"
      assert_includes row["tags"], "\\|"
      assert_equal [ @tag.name, tag2.name ].sort, Import::Row.new(tags: row["tags"]).tags_list.sort
    end
  end

  test "exported CSV files can generate matching import rows" do
    create_csv_export_trade!
    @account.entries.create!(
      name: "CSV Importable Transaction",
      amount: 15.25,
      currency: "USD",
      date: Date.parse("2024-05-16"),
      entryable: Transaction.new(category: @category)
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      accounts_csv = zip.read("accounts.csv")
      account_import = @other_family.imports.create!(
        type: "AccountImport",
        raw_file_str: accounts_csv,
        entity_type_col_label: "Account type*",
        name_col_label: "Name*",
        amount_col_label: "Balance*",
        currency_col_label: "Currency",
        date_col_label: "Balance Date",
        date_format: "%Y-%m-%d"
      )
      account_import.generate_rows_from_csv
      account_row = account_import.rows.reload.find_by!(name: @account.name)
      assert account_row.valid?
      assert_equal @account.accountable_type, account_row.entity_type
      assert_equal BigDecimal(@account.balance.to_s), BigDecimal(account_row.amount)
      assert account_row.date.blank?

      transaction_import = @other_family.imports.create!(
        type: "TransactionImport",
        raw_file_str: zip.read("transactions.csv"),
        date_col_label: "date*",
        amount_col_label: "amount*",
        name_col_label: "name",
        currency_col_label: "currency",
        category_col_label: "category",
        tags_col_label: "tags",
        account_col_label: "account",
        notes_col_label: "notes",
        date_format: "%Y-%m-%d",
        signage_convention: "inflows_negative"
      )
      transaction_import.generate_rows_from_csv
      transaction_row = transaction_import.rows.reload.find_by!(name: "CSV Importable Transaction")
      assert transaction_row.valid?
      assert_equal @account.name, transaction_row.account
      assert_equal BigDecimal("15.25"), transaction_row.signed_amount

      trade_import = @other_family.imports.create!(
        type: "TradeImport",
        raw_file_str: zip.read("trades.csv"),
        date_col_label: "date*",
        ticker_col_label: "ticker*",
        exchange_operating_mic_col_label: "exchange_operating_mic",
        currency_col_label: "currency",
        qty_col_label: "qty*",
        price_col_label: "price*",
        account_col_label: "account",
        name_col_label: "name",
        date_format: "%Y-%m-%d",
        signage_convention: "inflows_positive"
      )
      trade_import.generate_rows_from_csv
      trade_row = trade_import.rows.reload.find_by!(ticker: @csv_export_trade_ticker)
      assert trade_row.valid?
      assert_equal @account.name, trade_row.account
      assert_equal BigDecimal("10"), BigDecimal(trade_row.qty)
    end
  end

  test "generates valid NDJSON file" do
    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      lines.each do |line|
        assert_nothing_raised { JSON.parse(line) }
      end

      # Check that each line has expected structure
      first_line = JSON.parse(lines.first)
      assert first_line.key?("type")
      assert first_line.key?("data")
    end
  end

  test "only exports data from the specified family" do
    # Create data for another family that should NOT be exported
    other_account = @other_family.accounts.create!(
      name: "Other Family Account",
      accountable: Depository.new,
      balance: 5000,
      currency: "USD"
    )

    other_category = @other_family.categories.create!(
      name: "Other Family Category",
      color: "#0000FF"
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      # Check accounts.csv doesn't contain other family's data
      accounts_csv = zip.read("accounts.csv")
      assert accounts_csv.include?(@account.name)
      refute accounts_csv.include?(other_account.name)

      # Check categories.csv doesn't contain other family's data
      categories_csv = zip.read("categories.csv")
      assert categories_csv.include?(@category.name)
      refute categories_csv.include?(other_category.name)

      # Check NDJSON doesn't contain other family's data
      ndjson_content = zip.read("all.ndjson")
      refute ndjson_content.include?(other_account.id)
      refute ndjson_content.include?(other_category.id)
    end
  end

  test "exports rules in CSV format" do
    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      rules_csv = zip.read("rules.csv")

      assert rules_csv.include?("Test Rule")
      assert rules_csv.include?("transaction")
      assert rules_csv.include?("true")
    end
  end

  test "exports rules in NDJSON format with versioning" do
    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule"
      end

      assert rule_lines.any?

      rule_data = rule_lines.map { |line| JSON.parse(line) }.find { |rule| rule["data"]["name"] == "Test Rule" }

      assert_not_nil rule_data
      assert_equal "Rule", rule_data["type"]
      assert_equal 1, rule_data["version"]
      assert_equal @rule.id, rule_data["data"]["id"]
      assert rule_data["data"].key?("name")
      assert rule_data["data"].key?("resource_type")
      assert rule_data["data"].key?("active")
      assert_equal @rule.position, rule_data["data"]["position"]
      assert_equal false, rule_data["data"]["stop_processing"]
      assert_equal false, rule_data["data"]["apply_immediately"]
      assert rule_data["data"].key?("conditions")
      assert rule_data["data"].key?("actions")
    end
  end

  test "exports apply_immediately independently of stop_processing" do
    @rule.update!(apply_immediately: true)

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      rule_data = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }.find do |record|
        record["type"] == "Rule" && record["data"]["name"] == "Test Rule"
      end

      assert_equal false, rule_data["data"]["stop_processing"]
      assert_equal true, rule_data["data"]["apply_immediately"]
    end
  end

  test "exports the rule group name in CSV and NDJSON" do
    @rule.update!(rule_group: @family.rule_groups.create!(name: "Food"))

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      rules_csv = CSV.parse(zip.read("rules.csv"), headers: true)
      assert_equal "Food", rules_csv.find { |row| row["name"] == "Test Rule" }["group"]

      rule_line = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
        .find { |line| line["type"] == "Rule" && line["data"]["name"] == "Test Rule" }
      assert_equal "Food", rule_line["data"]["group"]
    end
  end

  test "exports rule conditions with proper structure" do
    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == "Test Rule"
      end

      assert rule_lines.any?

      rule_data = JSON.parse(rule_lines.first)
      conditions = rule_data["data"]["conditions"]

      assert_equal 1, conditions.length
      assert_equal "transaction_name", conditions[0]["condition_type"]
      assert_equal "like", conditions[0]["operator"]
      assert_equal "test", conditions[0]["value"]
    end
  end

  test "exports rule actions and maps category UUIDs to names" do
    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == "Test Rule"
      end

      assert rule_lines.any?

      rule_data = JSON.parse(rule_lines.first)
      actions = rule_data["data"]["actions"]

      assert_equal 1, actions.length
      assert_equal "set_transaction_category", actions[0]["action_type"]
      # Should export category name instead of UUID
      assert_equal "Test Category", actions[0]["value"]
      assert_equal({ "type" => "Category", "id" => @category.id, "name" => "Test Category" }, actions[0]["value_ref"])
    end
  end

  test "split rule round-trips through NDJSON into another family" do
    split_rule = create_split_rule!

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      rule_line = zip.read("all.ndjson").split("\n").find do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == split_rule.name
      end

      exported_value = JSON.parse(rule_line)["data"]["actions"].first["value"].to_json
      refute_includes exported_value, @category.id
      refute_includes exported_value, @tag.id

      existing_category = @other_family.categories.create!(name: "Test Category", color: "#FF0000")

      Family::DataImporter.new(@other_family, rule_line).import!

      assert_imported_split_rule(split_rule.name, category: existing_category)
    end
  end

  test "split rule round-trips through rules CSV into another family" do
    split_rule = create_split_rule!

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      import = @other_family.imports.create!(type: "RuleImport", raw_file_str: zip.read("rules.csv"), col_sep: ",")
      import.generate_rows_from_csv
      import.send(:import!)

      assert_imported_split_rule(split_rule.name, category: @other_family.categories.find_by!(name: "Test Category"))
    end
  end

  test "split rule with quotes in its names round-trips through rules CSV" do
    @category.update!(name: 'Kids "Fun" \\ Stuff')
    split_rule = create_split_rule!(row_name: 'My "half"')

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      import = @other_family.imports.create!(type: "RuleImport", raw_file_str: zip.read("rules.csv"), col_sep: ",")
      import.generate_rows_from_csv
      import.send(:import!)

      mine = imported_split_config(split_rule.name).first
      assert_equal 'My "half"', mine["name"]
      assert_equal @other_family.categories.find_by!(name: 'Kids "Fun" \\ Stuff').id, mine["category_id"]
    end
  end

  test "exports a split rule whose category was deleted without the stale id" do
    split_rule = create_split_rule!
    @category.destroy!

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      rule_line = zip.read("all.ndjson").split("\n").find do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == split_rule.name
      end

      splits = JSON.parse(rule_line)["data"]["actions"].first["value"]["splits"]
      assert_not splits.first.key?("category")
      assert_not splits.first.key?("category_id")
      assert_equal [ "Test Tag" ], splits.first["tags"]

      Family::DataImporter.new(@other_family, rule_line).import!

      split = imported_split_config(split_rule.name).first
      assert_nil split["category_id"]
      assert_equal [ @other_family.tags.find_by!(name: "Test Tag").id ], split["tag_ids"]
    end
  end

  test "exports rule condition value refs for mapped operands" do
    category_rule = @family.rules.build(
      name: "Category Condition Rule",
      resource_type: "transaction",
      active: true
    )
    category_rule.conditions.build(
      condition_type: "transaction_category",
      operator: "=",
      value: @category.id
    )
    category_rule.actions.build(action_type: "auto_categorize")
    category_rule.save!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      rule_data = zip.read("all.ndjson").split("\n").filter_map do |line|
        parsed = JSON.parse(line)
        parsed if parsed["type"] == "Rule" && parsed["data"]["name"] == "Category Condition Rule"
      end.first

      condition = rule_data["data"]["conditions"].first
      assert_equal "Test Category", condition["value"]
      assert_equal({ "type" => "Category", "id" => @category.id, "name" => "Test Category" }, condition["value_ref"])
    end
  end

  test "exports provider merchant rule operands by name" do
    provider_merchant = ProviderMerchant.create!(name: "Synced Grocer", source: "plaid")
    @account.entries.create!(
      date: Date.current, amount: 10, name: "Groceries", currency: "USD",
      entryable: Transaction.new(merchant: provider_merchant)
    )
    rule = @family.rules.build(name: "Provider Merchant Rule", resource_type: "transaction", active: true)
    rule.conditions.build(condition_type: "transaction_merchant", operator: "=", value: provider_merchant.id)
    rule.actions.build(action_type: "set_transaction_merchant", value: provider_merchant.id)
    rule.save!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      rule_data = zip.read("all.ndjson").split("\n").filter_map do |line|
        parsed = JSON.parse(line)
        parsed if parsed["type"] == "Rule" && parsed["data"]["name"] == "Provider Merchant Rule"
      end.first

      expected_ref = { "type" => "Merchant", "id" => provider_merchant.id, "name" => "Synced Grocer" }
      assert_equal "Synced Grocer", rule_data["data"]["conditions"].first["value"]
      assert_equal expected_ref, rule_data["data"]["conditions"].first["value_ref"]
      assert_equal "Synced Grocer", rule_data["data"]["actions"].first["value"]
      assert_equal expected_ref, rule_data["data"]["actions"].first["value_ref"]
    end
  end

  test "rule operand lookup matches uppercase UUID values" do
    operand = @exporter.send(
      :rule_operand,
      @category.id.upcase,
      type: "Category",
      relation: :categories,
      fallback_to_name: true
    )

    assert_equal "Test Category", operand[:value]
    assert_equal({ type: "Category", id: @category.id, name: "Test Category" }, operand[:value_ref])
  end

  test "rule operand lookup skips name fallback for stale UUID values" do
    stale_uuid = SecureRandom.uuid
    @exporter.expects(:operand_records_by_name).never

    operand = @exporter.send(
      :rule_operand,
      stale_uuid,
      type: "Category",
      relation: :categories,
      fallback_to_name: true
    )

    assert_equal stale_uuid, operand[:value]
    assert_nil operand[:value_ref]
  end

  test "operand id and name lookups for the same relation share a single query" do
    assert_queries_count(1) do
      @exporter.send(:operand_records_by_id, :categories)
      @exporter.send(:operand_records_by_name, :categories)
    end
  end

  test "exports rule actions and maps tag UUIDs to names" do
    # Create a rule with a tag action
    tag_rule = @family.rules.build(
      name: "Tag Rule",
      resource_type: "transaction",
      active: true
    )
    tag_rule.conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "test"
    )
    tag_rule.actions.build(
      action_type: "set_transaction_tags",
      value: @tag.id
    )
    tag_rule.save!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == "Tag Rule"
      end

      assert rule_lines.any?

      rule_data = JSON.parse(rule_lines.first)
      actions = rule_data["data"]["actions"]

      assert_equal 1, actions.length
      assert_equal "set_transaction_tags", actions[0]["action_type"]
      # Should export tag name instead of UUID
      assert_equal "Test Tag", actions[0]["value"]
      assert_equal({ "type" => "Tag", "id" => @tag.id, "name" => "Test Tag" }, actions[0]["value_ref"])
    end
  end

  test "exports rule actions with multiple tags and maps each tag UUID independently" do
    second_tag = @family.tags.create!(name: "Second Tag", color: "#0000FF")

    tag_rule = @family.rules.build(
      name: "Multi Tag Rule",
      resource_type: "transaction",
      active: true
    )
    tag_rule.conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "test"
    )
    tag_rule.actions.build(
      action_type: "set_transaction_tags",
      value: [ @tag.id, second_tag.id ]
    )
    tag_rule.save!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == "Multi Tag Rule"
      end

      assert rule_lines.any?

      rule_data = JSON.parse(rule_lines.first)
      actions = rule_data["data"]["actions"]

      assert_equal 1, actions.length
      # Should export both tag names, comma-separated, not a single opaque id string
      assert_equal "Test Tag,Second Tag", actions[0]["value"]
      assert_equal(
        [
          { "type" => "Tag", "id" => @tag.id, "name" => "Test Tag" },
          { "type" => "Tag", "id" => second_tag.id, "name" => "Second Tag" }
        ],
        actions[0]["value_ref"]
      )
    end
  end

  test "exports a multi-tag action's value CSV-quoted when a tag name contains a comma" do
    comma_tag = @family.tags.create!(name: "Food, Dining", color: "#0000FF")

    tag_rule = @family.rules.build(
      name: "Comma Tag Name Rule",
      resource_type: "transaction",
      active: true
    )
    tag_rule.conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "test"
    )
    tag_rule.actions.build(
      action_type: "set_transaction_tags",
      value: [ @tag.id, comma_tag.id ]
    )
    tag_rule.save!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == "Comma Tag Name Rule"
      end

      assert rule_lines.any?

      rule_data = JSON.parse(rule_lines.first)
      actions = rule_data["data"]["actions"]

      # The comma-containing name must be quoted so it round-trips as one
      # name rather than splitting into "Food" and " Dining" on import.
      assert_equal "Test Tag,\"Food, Dining\"", actions[0]["value"]
      assert_equal [ "Test Tag", "Food, Dining" ], CSV.parse_line(actions[0]["value"])
    end
  end

  test "exports a partially-orphaned multi-tag action's value_ref as an array" do
    second_tag = @family.tags.create!(name: "Second Tag", color: "#0000FF")

    tag_rule = @family.rules.build(
      name: "Orphaned Multi Tag Rule",
      resource_type: "transaction",
      active: true
    )
    tag_rule.conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "test"
    )
    tag_rule.actions.build(
      action_type: "set_transaction_tags",
      value: [ @tag.id, second_tag.id ]
    )
    tag_rule.save!

    second_tag.destroy!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == "Orphaned Multi Tag Rule"
      end

      assert rule_lines.any?

      rule_data = JSON.parse(rule_lines.first)
      actions = rule_data["data"]["actions"]

      assert_equal 1, actions.length
      # value_ref should stay an array (not collapse to a scalar Hash) even
      # though only one of the two original tag ids still resolves, so the
      # importer's array-handling branch keeps running instead of the
      # legacy single-tag scalar branch.
      assert_kind_of Array, actions[0]["value_ref"]
      assert_equal(
        [ { "type" => "Tag", "id" => @tag.id, "name" => "Test Tag" } ],
        actions[0]["value_ref"]
      )
    end
  end

  test "exports compound conditions with sub-conditions" do
    # Create a rule with compound conditions
    compound_rule = @family.rules.build(
      name: "Compound Rule",
      resource_type: "transaction",
      active: true
    )
    parent_condition = compound_rule.conditions.build(
      condition_type: "compound",
      operator: "or"
    )
    parent_condition.sub_conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "walmart"
    )
    parent_condition.sub_conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "target"
    )
    compound_rule.actions.build(
      action_type: "auto_categorize"
    )
    compound_rule.save!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      lines = ndjson_content.split("\n")

      rule_lines = lines.select do |line|
        parsed = JSON.parse(line)
        parsed["type"] == "Rule" && parsed["data"]["name"] == "Compound Rule"
      end

      assert rule_lines.any?

      rule_data = JSON.parse(rule_lines.first)
      conditions = rule_data["data"]["conditions"]

      assert_equal 1, conditions.length
      assert_equal "compound", conditions[0]["condition_type"]
      assert_equal "or", conditions[0]["operator"]
      assert_equal 2, conditions[0]["sub_conditions"].length
      assert_equal "walmart", conditions[0]["sub_conditions"][0]["value"]
      assert_equal "target", conditions[0]["sub_conditions"][1]["value"]
    end
  end

  test "exports valuation kind in NDJSON" do
    valuation_entry = @account.entries.create!(
      date: Date.parse("2020-04-01"),
      amount: 1000,
      name: "Opening balance",
      currency: "USD",
      entryable: Valuation.new(kind: "opening_anchor")
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      valuation_lines = ndjson_content.split("\n").select do |line|
        JSON.parse(line)["type"] == "Valuation"
      end

      assert valuation_lines.any?

      valuation_data = valuation_lines
        .map { |line| JSON.parse(line) }
        .find { |line| line.dig("data", "entry_id") == valuation_entry.id }

      assert valuation_data
      assert_equal "opening_anchor", valuation_data["data"]["kind"]
    end
  end

  test "exports recurring transactions in NDJSON" do
    merchant = @family.merchants.create!(name: "Internet Provider")
    recurring_transaction = @family.recurring_transactions.create!(
      account: @account,
      merchant: 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,
      payment_url: "https://pay.example.com/internet",
      expected_amount_min: -95,
      expected_amount_max: -85,
      expected_amount_avg: -89.99
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_content = zip.read("all.ndjson")
      recurring_data = ndjson_content
        .split("\n")
        .map { |line| JSON.parse(line) }
        .find { |line| line["type"] == "RecurringTransaction" && line.dig("data", "id") == recurring_transaction.id }

      assert recurring_data
      assert_equal recurring_transaction.id, recurring_data["data"]["id"]
      assert_equal @account.id, recurring_data["data"]["account_id"]
      assert_equal merchant.id, recurring_data["data"]["merchant_id"]
      assert_equal "-89.99", BigDecimal(recurring_data["data"]["amount"].to_s).to_s("F")
      assert_equal "active", recurring_data["data"]["status"]
      assert_equal true, recurring_data["data"]["manual"]
      assert_equal "https://pay.example.com/internet", recurring_data["data"]["payment_url"]
      assert_not recurring_data["data"].key?("family_id")
    end
  end

  test "exports provider merchants referenced by transactions in NDJSON" do
    provider_merchant = ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", provider_merchant_id: "plaid_amzn")
    @account.entries.create!(
      date: Date.parse("2024-05-02"),
      amount: 42.50,
      name: "Amazon purchase",
      currency: "USD",
      entryable: Transaction.new(merchant: provider_merchant)
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      provider_merchant_data = ndjson_records.find do |record|
        record["type"] == "ProviderMerchant" && record.dig("data", "id") == provider_merchant.id
      end

      assert provider_merchant_data
      assert_equal "AMZN MKTP", provider_merchant_data["data"]["name"]
      assert_equal "plaid", provider_merchant_data["data"]["source"]
      assert_equal "plaid_amzn", provider_merchant_data["data"]["provider_merchant_id"]
    end
  end

  test "does not export a color for a provider merchant" do
    provider_merchant = ProviderMerchant.create!(name: "Colorless", source: "plaid")
    @account.entries.create!(
      date: Date.parse("2024-05-02"), amount: 5, name: "Colorless purchase", currency: "USD",
      entryable: Transaction.new(merchant: provider_merchant)
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      data = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
        .find { |record| record["type"] == "ProviderMerchant" && record.dig("data", "id") == provider_merchant.id }["data"]

      assert_not data.key?("color")
    end
  end

  test "exports provider merchants referenced by recurring transactions in NDJSON" do
    provider_merchant = ProviderMerchant.create!(name: "Recurring Provider Merchant", source: "ai")
    @family.recurring_transactions.create!(
      account: @account,
      merchant: provider_merchant,
      amount: -12.99,
      currency: "USD",
      expected_day_of_month: 5,
      last_occurrence_date: Date.parse("2024-01-05"),
      next_expected_date: Date.parse("2024-02-05")
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      assert ndjson_records.any? { |record| record["type"] == "ProviderMerchant" && record.dig("data", "id") == provider_merchant.id }
    end
  end

  test "excludes provider merchants not referenced by the family from NDJSON" do
    unreferenced = ProviderMerchant.create!(name: "Unrelated Provider Merchant", source: "plaid")

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      refute ndjson_records.any? { |record| record["type"] == "ProviderMerchant" && record.dig("data", "id") == unreferenced.id }
    end
  end

  test "exports a user's choice to make an investment transfer a plain transfer" do
    brokerage = @family.accounts.create!(name: "Brokerage", accountable: Investment.new, balance: 0, currency: "USD")
    outflow = create_transaction_entry(@account, amount: 100, date: Date.parse("2024-01-15"), name: "To brokerage")
    inflow = create_transaction_entry(brokerage, amount: -100, date: Date.parse("2024-01-15"), name: "From checking")
    transfer = Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "confirmed")
    assert transfer.update_investment_contribution!(false)

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      transfer_data = ndjson_records.find { |record| record["type"] == "Transfer" && record.dig("data", "id") == transfer.id }

      assert_equal false, transfer_data["data"]["investment_contribution"]
    end
  end

  test "exports transfer decisions and rejected transfers in NDJSON" do
    destination_account = @family.accounts.create!(
      name: "Savings Account",
      accountable: Depository.new,
      balance: 0,
      currency: "USD"
    )

    transfer_outflow = create_transaction_entry(@account, amount: 100, date: Date.parse("2024-01-15"), name: "Transfer to savings")
    transfer_inflow = create_transaction_entry(destination_account, amount: -100, date: Date.parse("2024-01-15"), name: "Transfer from checking")
    transfer = Transfer.create!(
      outflow_transaction: transfer_outflow.entryable,
      inflow_transaction: transfer_inflow.entryable,
      status: "confirmed",
      notes: "Confirmed by user"
    )

    rejected_outflow = create_transaction_entry(@account, amount: 25, date: Date.parse("2024-01-20"), name: "Candidate outflow")
    rejected_inflow = create_transaction_entry(destination_account, amount: -25, date: Date.parse("2024-01-20"), name: "Candidate inflow")
    rejected_transfer = RejectedTransfer.create!(
      outflow_transaction: rejected_outflow.entryable,
      inflow_transaction: rejected_inflow.entryable
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }

      transfer_data = ndjson_records.find { |record| record["type"] == "Transfer" && record.dig("data", "id") == transfer.id }
      assert transfer_data
      assert_equal transfer_inflow.entryable.id, transfer_data["data"]["inflow_transaction_id"]
      assert_equal transfer_outflow.entryable.id, transfer_data["data"]["outflow_transaction_id"]
      assert_equal "confirmed", transfer_data["data"]["status"]
      assert_equal "Confirmed by user", transfer_data["data"]["notes"]
      assert_nil transfer_data["data"]["investment_contribution"]

      rejected_transfer_data = ndjson_records.find { |record| record["type"] == "RejectedTransfer" && record.dig("data", "id") == rejected_transfer.id }
      assert rejected_transfer_data
      assert_equal rejected_inflow.entryable.id, rejected_transfer_data["data"]["inflow_transaction_id"]
      assert_equal rejected_outflow.entryable.id, rejected_transfer_data["data"]["outflow_transaction_id"]

      # Transfer decisions must follow Transaction records so import can remap both sides.
      transaction_indices = ndjson_records.each_index.select { |index| ndjson_records[index]["type"] == "Transaction" }
      transfer_index = ndjson_records.index(transfer_data)
      rejected_transfer_index = ndjson_records.index(rejected_transfer_data)

      assert_operator transaction_indices.max, :<, transfer_index
      assert_operator transaction_indices.max, :<, rejected_transfer_index
    end
  end

  test "does not export transfer decisions for split parent transactions" do
    destination_account = @family.accounts.create!(
      name: "Split Transfer Savings",
      accountable: Depository.new,
      balance: 0,
      currency: "USD"
    )

    split_parent_outflow = create_transaction_entry(@account, amount: 104, date: Date.parse("2024-01-25"), name: "Split transfer parent")
    split_children = split_parent_outflow.split!([
      { name: "Split transfer child", amount: 100, category_id: @category.id },
      { name: "Split fee child", amount: 4, category_id: @category.id }
    ])
    parent_transfer_inflow = create_transaction_entry(destination_account, amount: -104, date: Date.parse("2024-01-25"), name: "Split parent transfer inflow")
    parent_transfer = Transfer.create!(
      outflow_transaction: split_parent_outflow.entryable,
      inflow_transaction: parent_transfer_inflow.entryable,
      status: "confirmed"
    )
    child_transfer_inflow = create_transaction_entry(destination_account, amount: -100, date: Date.parse("2024-01-25"), name: "Split child transfer inflow")
    child_transfer = Transfer.create!(
      outflow_transaction: split_children.first.entryable,
      inflow_transaction: child_transfer_inflow.entryable,
      status: "confirmed",
      notes: "Transfer uses split child"
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }

      transaction_ids = ndjson_records
        .select { |record| record["type"] == "Transaction" }
        .map { |record| record.dig("data", "id") }
      transfer_ids = ndjson_records
        .select { |record| record["type"] == "Transfer" }
        .map { |record| record.dig("data", "id") }

      assert_includes transaction_ids, split_parent_outflow.entryable.id
      split_parent_data = ndjson_records.find do |record|
        record["type"] == "Transaction" && record.dig("data", "id") == split_parent_outflow.entryable.id
      end
      assert_equal 2, split_parent_data.dig("data", "split_lines").count
      assert_equal [ "Split transfer child", "Split fee child" ], split_parent_data.dig("data", "split_lines").map { |line| line["name"] }
      refute_includes transaction_ids, split_children.first.entryable.id
      refute_includes transaction_ids, split_children.second.entryable.id
      assert_not_includes transfer_ids, parent_transfer.id

      child_transfer_data = ndjson_records.find { |record| record["type"] == "Transfer" && record.dig("data", "id") == child_transfer.id }
      assert child_transfer_data
      assert_equal split_children.first.entryable.id, child_transfer_data.dig("data", "outflow_transaction_id")
      assert_equal child_transfer_inflow.entryable.id, child_transfer_data.dig("data", "inflow_transaction_id")
    end
  end

  test "exports balance history in NDJSON for backup verification" do
    balance = @account.balances.create!(
      date: Date.parse("2024-01-15"),
      balance: 1234.56,
      cash_balance: 1234.56,
      start_cash_balance: 1000,
      start_non_cash_balance: 0,
      cash_inflows: 234.56,
      cash_outflows: 0,
      flows_factor: 1,
      currency: "USD"
    )

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      balance_data = ndjson_records.find { |record| record["type"] == "Balance" && record.dig("data", "id") == balance.id }

      assert balance_data
      assert_equal @account.id, balance_data["data"]["account_id"]
      assert_equal "2024-01-15", balance_data["data"]["date"]
      assert_equal "1234.56", BigDecimal(balance_data["data"]["balance"].to_s).to_s("F")
      assert_equal "USD", balance_data["data"]["currency"]
    end
  end

  test "exports balance history chronologically" do
    @account.balances.create!(date: Date.parse("2024-03-01"), balance: 300, flows_factor: 1, currency: "USD")
    @account.balances.create!(date: Date.parse("2024-01-01"), balance: 100, flows_factor: 1, currency: "USD")

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      balance_dates = zip.read("all.ndjson")
        .split("\n")
        .map { |line| JSON.parse(line) }
        .select { |record| record["type"] == "Balance" }
        .map { |record| Date.iso8601(record.dig("data", "date")) }

      assert_equal balance_dates.sort, balance_dates
    end
  end

  test "exports holding snapshots in NDJSON" do
    investment_account = @family.accounts.create!(
      name: "Investment Account",
      accountable: Investment.new,
      balance: 25_000,
      currency: "USD"
    )
    security = Security.create!(
      ticker: "VTI#{SecureRandom.hex(4).upcase}",
      name: "Vanguard Total Stock Market ETF",
      country_code: "US",
      exchange_operating_mic: "ARCX"
    )
    holding = investment_account.holdings.create!(
      security: 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 = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      ndjson_records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      holding_data = ndjson_records.find { |record| record["type"] == "Holding" && record.dig("data", "id") == holding.id }

      assert holding_data
      assert_equal investment_account.id, holding_data["data"]["account_id"]
      assert_equal security.id, holding_data["data"]["security_id"]
      assert_equal security.ticker, holding_data["data"]["ticker"]
      assert_equal "ARCX", holding_data["data"]["exchange_operating_mic"]
      assert_equal "2024-01-15", holding_data["data"]["date"]
      assert_equal "100.0", BigDecimal(holding_data["data"]["qty"].to_s).to_s("F")
      assert_equal "250.25", BigDecimal(holding_data["data"]["price"].to_s).to_s("F")
      assert_equal "25025.0", BigDecimal(holding_data["data"]["amount"].to_s).to_s("F")
      assert_equal "200.0", BigDecimal(holding_data["data"]["cost_basis"].to_s).to_s("F")
      assert_equal "manual", holding_data["data"]["cost_basis_source"]
      assert_equal true, holding_data["data"]["cost_basis_locked"]
      assert_not holding_data["data"].key?("created_at")
      assert_not holding_data["data"].key?("updated_at")
    end
  end

  test "only exports rules from the specified family" do
    # Create a rule for another family that should NOT be exported
    other_rule = @other_family.rules.build(
      name: "Other Family Rule",
      resource_type: "transaction",
      active: true
    )
    other_rule.conditions.build(
      condition_type: "transaction_name",
      operator: "like",
      value: "other"
    )
    other_rule.actions.build(
      action_type: "auto_categorize"
    )
    other_rule.save!

    zip_data = @exporter.generate_export

    Zip::File.open_buffer(zip_data) do |zip|
      # Check rules.csv doesn't contain other family's data
      rules_csv = zip.read("rules.csv")
      assert rules_csv.include?(@rule.name)
      refute rules_csv.include?(other_rule.name)

      # Check NDJSON doesn't contain other family's rules
      ndjson_content = zip.read("all.ndjson")
      assert ndjson_content.include?(@rule.name)
      refute ndjson_content.include?(other_rule.name)
    end
  end

  test "exports trade fee, activity label and stored exchange rate in NDJSON" do
    investment_account = @family.accounts.create!(
      name: "Tax Investment Account",
      accountable: Investment.new,
      balance: 10_000,
      currency: "EUR"
    )
    security = Security.create!(ticker: "TAX#{SecureRandom.hex(3).upcase}", name: "Tax Export Security")
    entry = investment_account.entries.create!(
      date: Date.parse("2024-05-20"),
      amount: 1002.5,
      name: "Buy",
      currency: "USD",
      entryable: Trade.new(
        security: security,
        qty: 10,
        price: 100,
        fee: 2.5,
        currency: "USD",
        investment_activity_label: "Buy",
        extra: { "exchange_rate" => 0.92, "ibkr" => { "account_id" => "U1234567" } }
      )
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      trade_data = records.find { |record| record["type"] == "Trade" && record.dig("data", "id") == entry.entryable.id }["data"]

      assert_equal "2.5", BigDecimal(trade_data["fee"].to_s).to_s("F")
      assert_equal "Buy", trade_data["investment_activity_label"]
      assert_equal 0.92, trade_data["exchange_rate"]
      assert_not trade_data.key?("extra")
      assert_not_includes zip.read("all.ndjson"), "U1234567"
    end
  end

  # The cost basis applies a trade's stored rate from currency (the trade's)
  # and the cash balance from the entry's currency, which an edit can make
  # differ. The rate is exported when either path applies it, with both
  # currencies named.
  test "exports the amount's currency next to the rate on trades and transactions" do
    investment_account = @family.accounts.create!(
      name: "Amount Currency Account",
      accountable: Investment.new,
      balance: 10_000,
      currency: "USD"
    )
    security = Security.create!(ticker: "AMC#{SecureRandom.hex(3).upcase}", name: "Amount Currency Security")
    # Only the cost basis applies the rate: the entry is in the account's currency.
    cost_basis_entry = investment_account.entries.create!(
      date: Date.parse("2024-05-20"),
      amount: 100,
      name: "Buy",
      currency: "USD",
      entryable: Trade.new(security: security, qty: 1, price: 100, currency: "EUR", investment_activity_label: "Buy",
        extra: { "exchange_rate" => 1.1 })
    )
    # Only the cash balance applies it: the trade is in the account's currency.
    cash_entry = investment_account.entries.create!(
      date: Date.parse("2024-05-20"),
      amount: -5,
      name: "Dividend",
      currency: "EUR",
      entryable: Trade.new(security: security, qty: 0, price: 0, currency: "USD", investment_activity_label: "Dividend",
        extra: { "exchange_rate" => 1.2 })
    )
    transaction_entry = investment_account.entries.create!(
      date: Date.parse("2024-05-21"),
      amount: -5,
      name: "Dividend",
      currency: "EUR",
      entryable: Transaction.new(investment_activity_label: "Dividend", extra: { "exchange_rate" => 1.1 })
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      data_for = ->(type, entry) { records.find { |record| record["type"] == type && record.dig("data", "id") == entry.entryable.id }["data"] }

      cost_basis_data = data_for.call("Trade", cost_basis_entry)
      assert_equal 1.1, cost_basis_data["exchange_rate"]
      assert_equal "EUR", cost_basis_data["currency"]
      assert_equal "USD", cost_basis_data["amount_currency"]

      cash_data = data_for.call("Trade", cash_entry)
      assert_equal 1.2, cash_data["exchange_rate"]
      assert_equal "USD", cash_data["currency"]
      assert_equal "EUR", cash_data["amount_currency"]

      transaction_data = data_for.call("Transaction", transaction_entry)
      assert_equal "EUR", transaction_data["amount_currency"]
      assert_equal 1.1, transaction_data["exchange_rate"]
    end
  end

  # numeric_exchange_rate reads each split line's account, which the export
  # preloads, so more split parents do not mean more account queries.
  test "split lines do not query accounts once per line" do
    make_split = lambda do
      parent = @account.entries.create!(date: Date.parse("2024-05-23"), amount: -10, name: "Split", currency: "EUR",
        entryable: Transaction.new)
      parent.split!([ { name: "A", amount: -6 }, { name: "B", amount: -4 } ]).each do |child|
        child.entryable.update_columns(extra: { "exchange_rate" => 1.08 })
      end
    end
    count_account_queries = lambda do
      count = 0
      callback = ->(*, payload) { count += 1 if payload[:sql].match?(/FROM "accounts"/) }
      ActiveSupport::Notifications.subscribed(callback, "sql.active_record") { @exporter.generate_export }
      count
    end

    make_split.call
    baseline = count_account_queries.call
    3.times { make_split.call }

    assert_equal baseline, count_account_queries.call
  end

  test "exports the activity label and safe provider fields on split lines" do
    security = Security.create!(ticker: "SPL#{SecureRandom.hex(3).upcase}", name: "Split Line Security")
    parent = @account.entries.create!(
      date: Date.parse("2024-05-22"),
      amount: -10,
      name: "Dividend to split",
      currency: "EUR",
      entryable: Transaction.new(investment_activity_label: "Dividend")
    )
    child = parent.split!([
      { name: "Dividend part", amount: -6 },
      { name: "Other part", amount: -4 }
    ]).first
    # Split children start without these; a provider or a later edit can
    # store them, as on any other row.
    child.update_columns(source: "ibkr")
    child.entryable.update_columns(
      investment_activity_label: "Dividend",
      extra: {
        "exchange_rate" => 1.08,
        "security_id" => security.id,
        "ibkr" => { "type" => "Dividends", "account_id" => "U5550001" }
      }
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      ndjson = zip.read("all.ndjson")
      records = ndjson.split("\n").map { |line| JSON.parse(line) }
      parent_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == parent.entryable.id }["data"]
      lines = parent_data["split_lines"]
      child_line = lines.find { |line| line["id"] == child.entryable.id }
      other_line = lines.find { |line| line["id"] != child.entryable.id }

      assert_equal "Dividend", child_line["investment_activity_label"]
      assert_equal "Dividends", child_line["provider_type"]
      assert_equal security.id, child_line["security_id"]
      assert_equal 1.08, child_line["exchange_rate"]
      assert_equal "EUR", child_line["amount_currency"]
      %w[investment_activity_label provider_type security_id exchange_rate].each do |field|
        assert other_line.key?(field), "expected #{field} on the split line"
        assert_nil other_line[field]
      end
      assert_not_includes ndjson, "U5550001"
    end
  end

  test "export reads a non-hash extra on a trade or transaction as null tax fields" do
    investment_account = @family.accounts.create!(
      name: "Malformed Extra Investment Account",
      accountable: Investment.new,
      balance: 10_000,
      currency: "EUR"
    )
    security = Security.create!(ticker: "TMX#{SecureRandom.hex(3).upcase}", name: "Malformed Extra Security")
    trade_entry = investment_account.entries.create!(
      date: Date.parse("2024-05-20"),
      amount: 500,
      name: "Buy",
      currency: "USD",
      entryable: Trade.new(security: security, qty: 5, price: 100, currency: "USD", investment_activity_label: "Buy")
    )
    transaction_entry = @account.entries.create!(
      date: Date.parse("2024-05-21"),
      amount: 1.5,
      name: "Malformed",
      currency: "EUR",
      source: "ibkr",
      entryable: Transaction.new
    )

    [ [ 1, 2 ], "raw-string-extra" ].each do |malformed|
      # Written past the model, as a provider or a migration writing SQL might.
      trade_entry.entryable.update_column(:extra, malformed)
      transaction_entry.entryable.update_column(:extra, malformed)

      Zip::File.open_buffer(@exporter.generate_export) do |zip|
        records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
        trade_data = records.find { |record| record["type"] == "Trade" && record.dig("data", "id") == trade_entry.entryable.id }["data"]
        transaction_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == transaction_entry.entryable.id }["data"]

        assert_nil trade_data["exchange_rate"]
        %w[provider_type security_id exchange_rate].each do |field|
          assert transaction_data.key?(field)
          assert_nil transaction_data[field], "expected #{field} to be null for extra = #{malformed.inspect}"
        end
      end
    end
  end

  test "exports transaction activity label and safe provider fields in NDJSON" do
    security = Security.create!(ticker: "WHX#{SecureRandom.hex(3).upcase}", name: "Withholding Export Security")
    entry = @account.entries.create!(
      date: Date.parse("2024-05-21"),
      amount: 1.5,
      name: "Withholding Tax",
      currency: "EUR",
      source: "ibkr",
      entryable: Transaction.new(
        investment_activity_label: "Dividend",
        extra: {
          "exchange_rate" => 0.93,
          "security_id" => security.id,
          "ibkr" => { "type" => "Withholding Tax", "conid" => "CONID-SECRET-2" }
        }
      )
    )
    plain_entry = @account.entries.create!(
      date: Date.parse("2024-05-22"),
      amount: 10,
      name: "Plain",
      currency: "USD",
      entryable: Transaction.new
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      records = zip.read("all.ndjson").split("\n").map { |line| JSON.parse(line) }
      transaction_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == entry.entryable.id }["data"]
      plain_data = records.find { |record| record["type"] == "Transaction" && record.dig("data", "id") == plain_entry.entryable.id }["data"]

      assert_equal "Dividend", transaction_data["investment_activity_label"]
      assert_equal "Withholding Tax", transaction_data["provider_type"]
      assert_equal security.id, transaction_data["security_id"]
      assert_equal 0.93, transaction_data["exchange_rate"]
      assert_not transaction_data.key?("extra")
      assert_not_includes zip.read("all.ndjson"), "CONID-SECRET-2"

      %w[investment_activity_label provider_type security_id exchange_rate].each do |field|
        assert plain_data.key?(field)
        assert_nil plain_data[field]
      end
    end
  end

  test "quotes every field so a locale separator inside text cannot start an unguarded cell" do
    @account.entries.create!(
      name: "Rent;=1+1",
      notes: "a\t=1+1|@SUM(1)",
      amount: 5,
      currency: "USD",
      date: Date.parse("2024-05-16"),
      entryable: Transaction.new
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      csv = zip.read("transactions.csv")
      assert_includes csv, %q("Rent;=1+1")
      assert_includes csv, %Q("a\t=1+1|@SUM(1)")
      assert csv.lines.first.start_with?(%q("date","account_name")), "header cells are quoted too"
      assert_equal "Rent;=1+1", CSV.parse(csv, headers: true).find { |row| row["name"].start_with?("Rent") }["name"]
    end
  end

  test "rule import keeps names that differ only by a leading apostrophe separate" do
    exported = nil
    Zip::File.open_buffer(@exporter.generate_export) { |zip| exported = CSV.parse(zip.read("rules.csv"), headers: true) }
    template = exported.find { |row| row["name"] == "Test Rule" }
    csv = CSV.generate do |out|
      out << exported.headers
      [ "=Rule", "'=Rule" ].each do |name|
        out << exported.headers.map { |header| header == "name" ? name : template[header] }
      end
    end

    import = @other_family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    assert_equal [ "'=Rule", "=Rule" ], import.rows.reload.map(&:name).sort
  end

  test "rules named with and without a leading apostrophe survive export and a committed import" do
    category = @family.categories.create!(name: "Rule Target", color: "#FF0000")
    other_category = @family.categories.create!(name: "Rule Other", color: "#00FF00")
    [ [ "=Rule", "first", category ], [ "'=Rule", "second", other_category ] ].each do |name, value, target|
      rule = @family.rules.build(name: name, resource_type: "transaction", active: true)
      rule.conditions.build(condition_type: "transaction_name", operator: "like", value: value)
      rule.actions.build(action_type: "set_transaction_category", value: target.id)
      rule.save!
    end

    csv = nil
    Zip::File.open_buffer(@exporter.generate_export) { |zip| csv = zip.read("rules.csv") }
    target_category = @other_family.categories.create!(name: "Rule Target", color: "#FF0000")
    @other_family.categories.create!(name: "Rule Other", color: "#00FF00")
    import = @other_family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
    import.generate_rows_from_csv
    import.send(:import!)

    rules = @other_family.rules.where(name: [ "'=Rule", "''=Rule" ]).index_by(&:name)
    assert_equal [ "''=Rule", "'=Rule" ], rules.keys.sort
    assert_equal [ "first" ], rules["'=Rule"].conditions.map(&:value)
    assert_equal [ "second" ], rules["''=Rule"].conditions.map(&:value)
    assert_equal target_category.id, rules["'=Rule"].actions.first.value
  end

  test "rule operands spell escaped category names exactly as the other CSVs do" do
    budget = @family.categories.create!(name: "=Budget", color: "#FF0000")
    rule = @family.rules.build(name: "Budget Rule", resource_type: "transaction", active: true)
    rule.conditions.build(condition_type: "transaction_category", operator: "=", value: budget.id)
    rule.actions.build(action_type: "set_transaction_category", value: budget.id)
    rule.save!
    @account.entries.create!(
      name: "Budget purchase", amount: 9, currency: "USD", date: Date.parse("2024-05-16"),
      entryable: Transaction.new(category: budget)
    )

    files = {}
    ndjson = nil
    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      %w[categories transactions rules].each { |name| files[name] = zip.read("#{name}.csv") }
      ndjson = zip.read("all.ndjson")
    end

    rule_row = CSV.parse(files["rules"], headers: true).find { |row| row["name"] == "Budget Rule" }
    assert_equal "'=Budget", JSON.parse(rule_row["conditions"]).first["value"]
    assert_equal "'=Budget", JSON.parse(rule_row["actions"]).first["value"]
    assert_includes ndjson, '"=Budget"', "all.ndjson keeps the raw name"

    [ [ "CategoryImport", "categories" ], [ "RuleImport", "rules" ] ].each do |type, file|
      import = @other_family.imports.create!(type: type, raw_file_str: files[file], col_sep: ",")
      import.generate_rows_from_csv
      import.send(:import!)
    end

    assert_equal 1, @other_family.categories.where(name: "'=Budget").count
    imported = @other_family.rules.find_by!(name: "Budget Rule")
    assert_equal "'=Budget", @other_family.categories.find(imported.actions.first.value).name
  end

  # CSV formula injection (CWE-1236) -------------------------------------------
  #
  # These assert on the emitted CSV rather than on the helper. Sanitizing field
  # by field is how fields get missed, so each generator is checked for the
  # columns a user controls.

  test "every CSV in the export escapes formula-triggering user content" do
    security = Security.create!(ticker: "=SUM(A1)", name: "Formula Security", exchange_operating_mic: "XNAS")
    account = @family.accounts.create!(
      name: "@evil account",
      accountable: Depository.new(subtype: "=cmd"),
      balance: 500,
      currency: "USD"
    )
    account.entries.create!(
      date: Date.parse("2024-05-18"), amount: 1500, name: "Formula Trade", currency: "USD",
      entryable: Trade.new(security: security, qty: 10, price: 150, currency: "USD")
    )
    category = @family.categories.create!(name: "+cmd|calc", color: "#123456", lucide_icon: "@icon")
    account.entries.create!(
      date: Date.parse("2024-05-19"), amount: 10, currency: "USD",
      name: "=SUM(B1)", notes: "-1.5x leverage",
      entryable: Transaction.new(category: category)
    )
    @family.merchants.create!(name: "-2+3", color: "#123456")
    @family.rules.create!(
      name: "@rule",
      resource_type: "transaction",
      actions: [ Rule::Action.new(action_type: "set_transaction_category", value: category.id) ]
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      accounts = CSV.parse(zip.read("accounts.csv"), headers: true)
      row = accounts.find { |r| r["name"] == "'@evil account" }
      assert row, "account name must be escaped"
      assert_equal "'=cmd", row["subtype"], "account subtype must be escaped"

      trades = CSV.parse(zip.read("trades.csv"), headers: true)
      assert trades.any? { |r| r["ticker"] == "'=SUM(A1)" }, "trade ticker must be escaped"
      assert_not trades.any? { |r| r["ticker"] == "=SUM(A1)" }, "raw formula ticker must not appear"

      categories = CSV.parse(zip.read("categories.csv"), headers: true)
      row = categories.find { |r| r["name"] == "'+cmd|calc" }
      assert row, "category name must be escaped"
      assert_equal "'@icon", row["lucide_icon"], "category lucide_icon must be escaped"

      transactions = CSV.parse(zip.read("transactions.csv"), headers: true)
      row = transactions.find { |r| r["name"] == "'=SUM(B1)" }
      assert row, "transaction name must be escaped"
      assert_equal "'-1.5x leverage", row["notes"], "transaction notes must be escaped"

      merchants = CSV.parse(zip.read("merchants.csv"), headers: true)
      assert merchants.any? { |r| r["name"] == "'-2+3" }, "merchant name must be escaped"

      rules = CSV.parse(zip.read("rules.csv"), headers: true)
      assert rules.any? { |r| r["name"] == "'@rule" }, "rule name must be escaped"
    end
  end

  # A bare number cannot run anything, and escaping it would turn every income
  # amount, negative balance and sale quantity into text in the spreadsheet.
  test "CSV export leaves negative numbers as numbers" do
    account = @family.accounts.create!(name: "Overdrawn", accountable: Depository.new, balance: -250.5, currency: "USD")
    account.entries.create!(
      date: Date.parse("2024-05-19"), amount: -1200, currency: "USD", name: "Salary",
      entryable: Transaction.new
    )
    security = Security.create!(ticker: "SELLME", name: "Sold Security", exchange_operating_mic: "XNAS")
    account.entries.create!(
      date: Date.parse("2024-05-20"), amount: -300, name: "Sell", currency: "USD",
      entryable: Trade.new(security: security, qty: -2, price: 150, currency: "USD")
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      accounts = CSV.parse(zip.read("accounts.csv"), headers: true)
      assert_equal "-250.5", accounts.find { |r| r["name"] == "Overdrawn" }["balance"]

      transactions = CSV.parse(zip.read("transactions.csv"), headers: true)
      assert_equal "-1200.0", transactions.find { |r| r["name"] == "Salary" }["amount"]

      trade = CSV.parse(zip.read("trades.csv"), headers: true).find { |r| r["ticker"] == "SELLME" }
      assert_equal "-2.0", trade["quantity"]
      assert_equal "-300.0", trade["amount"]
    end
  end

  test "NDJSON keeps formula-prefixed values verbatim so export and import round-trip" do
    name  = "=SUM(A1)"
    notes = "-1.5x leverage"
    entry = @account.entries.create!(
      date: Date.current, name: name, amount: 10, currency: "USD", notes: notes,
      entryable: Transaction.new
    )

    Zip::File.open_buffer(@exporter.generate_export) do |zip|
      line = zip.read("all.ndjson").each_line.find do |l|
        parsed = JSON.parse(l)
        parsed["type"] == "Transaction" && parsed.dig("data", "entry_id") == entry.id
      end

      assert line, "the transaction must be in all.ndjson"
      data = JSON.parse(line)["data"]
      assert_equal name, data["name"]
      assert_equal notes, data["notes"]
    end
  end

  private

    def create_transaction_entry(account, amount:, date:, name:)
      account.entries.create!(
        date: date,
        amount: amount,
        name: name,
        currency: account.currency,
        entryable: Transaction.new(kind: "funds_movement")
      )
    end

    def create_split_rule!(row_name: "Mine")
      merchant = @family.merchants.create!(name: "Split Merchant")
      rule = @family.rules.build(name: "Split Rule", resource_type: "transaction", active: true)
      rule.conditions.build(condition_type: "transaction_name", operator: "like", value: "shared")
      rule.actions.build(
        action_type: "split_transaction",
        value: {
          splits: [
            { type: "percentage", name: row_name, share: "60", category_id: @category.id, merchant_id: merchant.id, tag_ids: [ @tag.id ] },
            { type: "percentage", name: "Theirs", share: "40", category_id: nil, merchant_id: nil, tag_ids: [] }
          ]
        }.to_json
      )
      rule.save!
      rule
    end

    def imported_split_config(rule_name)
      action = @other_family.rules.find_by!(name: rule_name).actions.sole
      assert_equal "split_transaction", action.action_type
      JSON.parse(action.value)["splits"]
    end

    def assert_imported_split_rule(rule_name, category:)
      mine, theirs = imported_split_config(rule_name)

      assert_equal [ "percentage", "Mine", "60" ], mine.values_at("type", "name", "share")
      assert_equal category.id, mine["category_id"]
      assert_equal @other_family.merchants.find_by!(name: "Split Merchant").id, mine["merchant_id"]
      assert_equal [ @other_family.tags.find_by!(name: "Test Tag").id ], mine["tag_ids"]
      assert_nil theirs["category_id"]
      assert_nil theirs["merchant_id"]
      assert_equal [], theirs["tag_ids"]
    end

    def create_csv_export_trade!
      security = Security.create!(
        ticker: "CSV#{SecureRandom.hex(3).upcase}",
        name: "CSV Export Security",
        exchange_operating_mic: "XNAS"
      )
      @csv_export_trade_ticker = security.ticker

      @account.entries.create!(
        date: Date.parse("2024-05-17"),
        amount: 1500,
        name: "CSV Export Buy",
        currency: "USD",
        entryable: Trade.new(
          security: security,
          qty: 10,
          price: 150,
          currency: "USD"
        )
      )
    end
end