Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
76.8 KB
Raw Blame
# frozen_string_literal: true

require "test_helper"

class Api::V1::TransactionsControllerTest < ActionDispatch::IntegrationTest
  include EntriesTestHelper

  setup do
    @user = users(:family_admin)
    @family = @user.family
    @account = @family.accounts.first
    @transaction = transactions(:one)

    # Destroy existing active API keys to avoid validation errors
    @user.api_keys.active.destroy_all

    # Create fresh API keys instead of using fixtures to avoid parallel test conflicts (rate limiting in test)
    @api_key = ApiKey.create!(
      user: @user,
      name: "Test Read-Write Key",
      scopes: [ "read_write" ],
      display_key: "test_rw_#{SecureRandom.hex(8)}"
    )

    @read_only_api_key = ApiKey.create!(
      user: @user,
      name: "Test Read-Only Key",
      scopes: [ "read" ],
      display_key: "test_ro_#{SecureRandom.hex(8)}",
      source: "mobile"  # Use different source to allow multiple keys
    )

    # Clear any existing rate limit data
    Redis.new.del("api_rate_limit:#{@api_key.id}")
    Redis.new.del("api_rate_limit:#{@read_only_api_key.id}")
  end

  # INDEX action tests
  test "should get index with valid API key" do
    get api_v1_transactions_url, headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    assert response_data.key?("transactions")
    assert response_data.key?("pagination")

    # Agent-friendly numeric fields (validate type + sign invariants)
    first = response_data["transactions"].first
    assert_amount_cents_fields(first)
    assert response_data["pagination"].key?("page")
    assert response_data["pagination"].key?("per_page")
    assert response_data["pagination"].key?("total_count")
    assert response_data["pagination"].key?("total_pages")
  end

  test "index avoids per-transaction transfer queries" do
    from_account = @family.accounts.first
    to_account = @family.accounts.second || @family.accounts.create!(
      name: "Second Account",
      balance: 0,
      currency: @family.currency,
      accountable: Depository.new
    )

    create_transfer(from_account: from_account, to_account: to_account, amount: 10)
    baseline_queries = count_db_queries do
      get api_v1_transactions_url, params: { per_page: 200 }, headers: api_headers(@api_key)
      assert_response :success
    end

    5.times { create_transfer(from_account: from_account, to_account: to_account, amount: 10) }
    expanded_queries = count_db_queries do
      get api_v1_transactions_url, params: { per_page: 200 }, headers: api_headers(@api_key)
      assert_response :success
    end

    assert_equal baseline_queries, expanded_queries
  end

  test "should get index with read-only API key" do
    get api_v1_transactions_url, headers: api_headers(@read_only_api_key)
    assert_response :success
  end

  test "should filter transactions by account_id" do
    get api_v1_transactions_url, params: { account_id: @account.id }, headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    response_data["transactions"].each do |transaction|
      assert_equal @account.id, transaction["account"]["id"]
    end
  end

  test "should include disabled account transactions in index history" do
    disabled_transaction = create_disabled_account_transaction(name: "Closed Account Grocery")

    get api_v1_transactions_url, headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    transaction_ids = response_data["transactions"].map { |transaction| transaction["id"] }
    assert_includes transaction_ids, disabled_transaction.id
  end

  test "should exclude pending deletion account transactions from index history" do
    pending_deletion_transaction = create_account_transaction(
      status: "pending_deletion",
      name: "Pending Delete Account Grocery"
    )

    get api_v1_transactions_url, headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    transaction_ids = response_data["transactions"].map { |transaction| transaction["id"] }
    assert_not_includes transaction_ids, pending_deletion_transaction.id
  end

  test "should filter disabled account transactions by account_id" do
    disabled_transaction = create_disabled_account_transaction(name: "Closed Account Filter")
    disabled_account = disabled_transaction.entry.account

    get api_v1_transactions_url,
        params: { account_id: disabled_account.id },
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    assert_equal [ disabled_transaction.id ], response_data["transactions"].map { |transaction| transaction["id"] }
  end

  test "should filter transactions by date range" do
    start_date = 1.month.ago.to_date
    end_date = Date.current

    get api_v1_transactions_url,
        params: { start_date: start_date, end_date: end_date },
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    response_data["transactions"].each do |transaction|
      transaction_date = Date.parse(transaction["date"])
      assert transaction_date >= start_date
      assert transaction_date <= end_date
    end
  end

  test "should filter transactions by tag_ids without error" do
    tag_one = tags(:one)
    tag_two = tags(:two)
    tagged_entry = @account.entries.create!(
      name: "Tagged Transaction",
      amount: 12.34,
      currency: "USD",
      date: Date.current,
      entryable: Transaction.new(tags: [ tag_one, tag_two ])
    )

    untagged_entry = @account.entries.create!(
      name: "Untagged Transaction",
      amount: 12.34,
      currency: "USD",
      date: Date.current,
      entryable: Transaction.new
    )

    get api_v1_transactions_url,
        params: { tag_ids: [ tag_one.id, tag_two.id ], per_page: 200 },
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    transaction_ids = response_data["transactions"].map { |t| t["id"] }
    assert_equal 1, transaction_ids.count(tagged_entry.transaction.id)
    assert_includes transaction_ids, tagged_entry.transaction.id
    assert_not_includes transaction_ids, untagged_entry.transaction.id
  end

  test "should filter disabled account transactions by date range" do
    disabled_transaction = create_disabled_account_transaction(
      name: "Closed Account Date Range",
      date: Date.current - 3.days
    )

    get api_v1_transactions_url,
        params: { start_date: Date.current - 4.days, end_date: Date.current - 2.days },
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    transaction_ids = response_data["transactions"].map { |transaction| transaction["id"] }
    assert_includes transaction_ids, disabled_transaction.id
  end

  test "should search transactions" do
    # Create a transaction with a specific name for testing
    entry = @account.entries.create!(
      name: "Test Coffee Purchase",
      amount: 5.50,
      currency: "USD",
      date: Date.current,
      entryable: Transaction.new
    )

    get api_v1_transactions_url,
        params: { search: "Coffee" },
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    found_transaction = response_data["transactions"].find { |t| t["id"] == entry.transaction.id }
    assert_not_nil found_transaction, "Should find the coffee transaction"
  end

  # The search term is interpolated into an ILIKE pattern, so "%" and "_" from
  # the caller act as wildcards instead of literals. Unescaped, a search for
  # "%" matches every transaction in the family rather than the ones that
  # actually contain a percent sign.
  test "search treats LIKE wildcards in the term as literal characters" do
    literal = @account.entries.create!(
      name: "100% cotton",
      amount: 5.50, currency: "USD", date: Date.current, entryable: Transaction.new
    )
    other = @account.entries.create!(
      name: "Plain coffee",
      amount: 5.50, currency: "USD", date: Date.current, entryable: Transaction.new
    )

    get api_v1_transactions_url,
        params: { search: "%" },
        headers: api_headers(@api_key)
    assert_response :success

    ids = JSON.parse(response.body)["transactions"].map { |t| t["id"] }
    assert_includes ids, literal.transaction.id, "the transaction containing a literal % must match"
    assert_not_includes ids, other.transaction.id, "a bare % must not match every transaction"
  end

  test "should search disabled account transactions" do
    disabled_transaction = create_disabled_account_transaction(name: "Closed Account Coffee")

    get api_v1_transactions_url,
        params: { search: "Closed Account Coffee" },
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    found_transaction = response_data["transactions"].find { |transaction| transaction["id"] == disabled_transaction.id }
    assert_not_nil found_transaction, "Should find disabled account transactions in global history search"
  end

  test "should paginate transactions" do
    get api_v1_transactions_url,
        params: { page: 1, per_page: 5 },
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    assert response_data["transactions"].size <= 5
    assert_equal 1, response_data["pagination"]["page"]
    assert_equal 5, response_data["pagination"]["per_page"]
  end

  test "should reject index request without API key" do
    get api_v1_transactions_url
    assert_response :unauthorized
  end

  test "should reject index request with invalid API key" do
    get api_v1_transactions_url, headers: { "X-Api-Key" => "invalid-key" }
    assert_response :unauthorized
  end

  # SHOW action tests
  test "should show transaction with valid API key" do
    get api_v1_transaction_url(@transaction), headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    assert_equal @transaction.id, response_data["id"]
    assert_equal @transaction.entry.id, response_data["entry_id"]
    assert response_data.key?("name")
    assert response_data.key?("amount")
    assert_amount_cents_fields(response_data)
    assert response_data.key?("date")
    assert response_data.key?("account")
  end

  test "should show transaction with read-only API key" do
    get api_v1_transaction_url(@transaction), headers: api_headers(@read_only_api_key)
    assert_response :success
  end

  test "should show disabled account transaction" do
    disabled_transaction = create_disabled_account_transaction(name: "Closed Account Show")

    get api_v1_transaction_url(disabled_transaction), headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    assert_equal disabled_transaction.id, response_data["id"]
    assert_equal disabled_transaction.entry.account_id, response_data["account"]["id"]
  end

  test "should return 404 for valid missing transaction id" do
    get api_v1_transaction_url(SecureRandom.uuid), headers: api_headers(@api_key)
    assert_response :not_found

    response_data = JSON.parse(response.body)
    assert_equal "not_found", response_data["error"]
    assert_equal "Transaction not found", response_data["message"]
  end

  test "should return 404 for malformed id" do
    get api_v1_transaction_url(999999), headers: api_headers(@api_key)
    assert_response :not_found

    response_data = JSON.parse(response.body)
    assert_equal "not_found", response_data["error"]
    assert_equal "Transaction not found", response_data["message"]
  end

  test "should reject show request without API key" do
    get api_v1_transaction_url(@transaction)
    assert_response :unauthorized
  end

  # CREATE action tests
  test "should create transaction with valid parameters" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Test Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense"
      }
    }

    assert_difference("@account.entries.count", 1) do
      post api_v1_transactions_url,
           params: transaction_params,
           headers: api_headers(@api_key)
    end

    assert_response :created
    response_data = JSON.parse(response.body)
    assert_equal "Test Transaction", response_data["name"]
    assert_equal @account.id, response_data["account"]["id"]
  end

  test "creating and updating via the API runs rules set to apply immediately" do
    @family.rules.create!(
      resource_type: "transaction", active: true, apply_immediately: true,
      conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "API") ],
      actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @family.categories.first.id) ]
    )

    post api_v1_transactions_url,
         params: { transaction: { account_id: @account.id, name: "API purchase", amount: 5, date: Date.current, currency: "USD", nature: "expense" } },
         headers: api_headers(@api_key)
    assert_response :created
    created_id = JSON.parse(response.body)["id"]
    assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @family, { transaction_ids: [ created_id ] } ])

    put api_v1_transaction_url(@transaction), params: { transaction: { name: "API rename" } }, headers: api_headers(@api_key)
    assert_response :success
    assert_enqueued_with(job: ApplyImmediateRulesJob, args: [ @family, { transaction_ids: [ @transaction.id ] } ])
  end

  test "an API update that changes nothing runs no immediate rules" do
    @family.rules.create!(
      resource_type: "transaction", active: true, apply_immediately: true,
      conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "API") ],
      actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @family.categories.first.id) ]
    )

    put api_v1_transaction_url(@transaction), params: { transaction: { name: @transaction.entry.name } }, headers: api_headers(@api_key)

    assert_response :success
    assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)
  end

  test "a rejected API update runs no immediate rules" do
    @family.rules.create!(
      resource_type: "transaction", active: true, apply_immediately: true,
      conditions: [ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "API") ],
      actions: [ Rule::Action.new(action_type: "set_transaction_category", value: @family.categories.first.id) ]
    )

    put api_v1_transaction_url(@transaction), params: { transaction: { name: "" } }, headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_no_enqueued_jobs(only: ApplyImmediateRulesJob)
  end

  test "should create transaction with external idempotency key" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense",
        external_id: "import-txn-1",
        source: "external_import"
      }
    }

    assert_difference("@account.entries.count", 1) do
      post api_v1_transactions_url,
           params: transaction_params,
           headers: api_headers(@api_key)
    end

    assert_response :created
    response_data = JSON.parse(response.body)
    assert_equal "import-txn-1", response_data["external_id"]
    assert_equal "external_import", response_data["source"]

    entry = @account.entries.find_by!(external_id: "import-txn-1", source: "external_import")
    assert_equal response_data["id"], entry.transaction.id
  end

  test "should create transaction protected from provider sync when user_modified is true" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense",
        user_modified: true
      }
    }

    assert_difference("@account.entries.count", 1) do
      post api_v1_transactions_url,
           params: transaction_params,
           headers: api_headers(@api_key)
    end

    assert_response :created
    response_data = JSON.parse(response.body)
    assert_equal true, response_data["user_modified"]

    entry = Transaction.find(response_data["id"]).entry
    assert entry.user_modified?
    assert entry.protected_from_sync?
  end

  test "should not mark transaction user_modified by default" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense"
      }
    }

    post api_v1_transactions_url, params: transaction_params, headers: api_headers(@api_key)

    assert_response :created
    response_data = JSON.parse(response.body)
    assert_equal false, response_data["user_modified"]
  end

  test "should use default source when external_id provided without source" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense",
        external_id: "default-source-test"
      }
    }

    assert_difference("@account.entries.count", 1) do
      post api_v1_transactions_url,
           params: transaction_params,
           headers: api_headers(@api_key)
    end

    assert_response :created
    response_data = JSON.parse(response.body)
    entry = @account.entries.find_by!(external_id: "default-source-test")
    assert_equal "api", entry.source
    assert_equal "api", response_data["source"]

    assert_no_difference("@account.entries.count") do
      post api_v1_transactions_url,
           params: transaction_params.deep_merge(transaction: { name: "Changed Name" }),
           headers: api_headers(@api_key)
    end

    assert_response :ok
  end

  test "should reject source without external idempotency key" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense",
        source: "external_import"
      }
    }

    assert_no_difference("@account.entries.count") do
      post api_v1_transactions_url,
           params: transaction_params,
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    response_data = JSON.parse(response.body)
    assert_equal "validation_failed", response_data["error"]
    assert_equal "Source requires external_id", response_data["message"]
    assert_equal [ "Source requires external_id" ], response_data["errors"]
  end

  test "should return existing transaction for duplicate external idempotency key" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense",
        external_id: "import-txn-2",
        source: "external_import"
      }
    }

    post api_v1_transactions_url,
         params: transaction_params,
         headers: api_headers(@api_key)
    assert_response :created
    created_data = JSON.parse(response.body)

    assert_no_difference("@account.entries.count") do
      post api_v1_transactions_url,
           params: transaction_params.deep_merge(transaction: { name: "Changed Name" }),
           headers: api_headers(@api_key)
    end

    assert_response :ok
    response_data = JSON.parse(response.body)
    assert_equal created_data["id"], response_data["id"]
    assert_equal "Imported Transaction", response_data["name"]
  end

  test "should scope external idempotency keys to account" do
    other_account = @family.accounts.create!(
      name: "Other API Account",
      accountable: Depository.new,
      balance: 0,
      currency: "USD"
    )
    transaction_params = {
      transaction: {
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense",
        external_id: "shared-import-txn",
        source: "external_import"
      }
    }

    assert_difference("Entry.count", 2) do
      post api_v1_transactions_url,
           params: transaction_params.deep_merge(transaction: { account_id: @account.id }),
           headers: api_headers(@api_key)
      assert_response :created

      post api_v1_transactions_url,
           params: transaction_params.deep_merge(transaction: { account_id: other_account.id }),
           headers: api_headers(@api_key)
      assert_response :created
    end
  end

  test "should scope external idempotency keys to source" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Imported Transaction",
        amount: 25.00,
        date: Date.current,
        currency: "USD",
        nature: "expense",
        external_id: "shared-source-txn",
        source: "external_import"
      }
    }

    assert_difference("Entry.count", 2) do
      post api_v1_transactions_url,
           params: transaction_params,
           headers: api_headers(@api_key)
      assert_response :created

      post api_v1_transactions_url,
           params: transaction_params.deep_merge(transaction: { source: "other_import" }),
           headers: api_headers(@api_key)
      assert_response :created
    end

    @account.entries.find_by!(external_id: "shared-source-txn", source: "external_import")
    @account.entries.find_by!(external_id: "shared-source-txn", source: "other_import")
  end

  test "should reject external idempotency key collision with non-transaction entry" do
    @account.entries.create!(
      name: "Existing valuation",
      amount: 100,
      currency: "USD",
      date: Date.current,
      external_id: "import-non-transaction",
      source: "external_import",
      entryable: Valuation.new
    )

    post api_v1_transactions_url,
         params: {
           transaction: {
             account_id: @account.id,
             name: "Imported Transaction",
             amount: 25.00,
             date: Date.current - 1.day,
             currency: "USD",
             nature: "expense",
             external_id: "import-non-transaction",
             source: "external_import"
           }
         },
         headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    response_data = JSON.parse(response.body)
    assert_equal "validation_failed", response_data["error"]
  end

  test "should reject create with read-only API key" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Test Transaction",
        amount: 25.00,
        date: Date.current
      }
    }

    post api_v1_transactions_url,
         params: transaction_params,
         headers: api_headers(@read_only_api_key)
    assert_response :forbidden
  end

  test "should reject create with invalid parameters" do
    transaction_params = {
      transaction: {
        # Missing required fields
        name: "Test Transaction"
      }
    }

    post api_v1_transactions_url,
         params: transaction_params,
         headers: api_headers(@api_key)
    assert_response :unprocessable_entity
  end

  test "should reject invalid date on create" do
    transaction_params = {
      transaction: {
        account_id: @account.id,
        name: "Invalid Date Transaction",
        amount: 25.00,
        date: "not-a-date",
        currency: "USD",
        nature: "expense"
      }
    }

    assert_no_difference("@account.entries.count") do
      post api_v1_transactions_url,
           params: transaction_params,
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    response_data = JSON.parse(response.body)
    assert_equal "validation_failed", response_data["error"]
    assert_equal "Transaction could not be created", response_data["message"]
    assert response_data["errors"].any? { |error| error.match?(/Date/) }
  end

  test "should reject create without API key" do
    post api_v1_transactions_url, params: { transaction: { name: "Test" } }
    assert_response :unauthorized
  end

  # UPDATE action tests
  test "should update transaction with valid parameters" do
    update_params = {
      transaction: {
        name: "Updated Transaction Name",
        amount: 30.00
      }
    }

    put api_v1_transaction_url(@transaction),
        params: update_params,
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    assert_equal "Updated Transaction Name", response_data["name"]
  end

  test "update with only a nature applies it to the stored amount" do
    entry = create_transaction(account: @account, amount: 40, name: "Nature only")

    [ [ "income", -40 ], [ "inflow", -40 ], [ "expense", 40 ], [ "outflow", 40 ] ].each do |nature, expected|
      put api_v1_transaction_url(entry.transaction), params: { transaction: { nature: nature } }, headers: api_headers(@api_key)

      assert_response :success, nature
      assert_equal expected, entry.reload.amount, nature
    end
  end

  test "update with only a nature syncs the account when the sign flips" do
    entry = create_transaction(account: @account, amount: 40, name: "Nature flip")

    assert_enqueued_with(job: SyncJob) do
      put api_v1_transaction_url(entry.transaction), params: { transaction: { nature: "income" } }, headers: api_headers(@api_key)
    end
    assert_response :success
  end

  test "update refuses a nature or amount that would break a transfer's legs" do
    transfer = create_transfer_between_accounts
    outflow = transfer.outflow_transaction.entry
    inflow = transfer.inflow_transaction.entry

    [ { nature: "income" }, { amount: 120 }, { amount: 100, nature: "inflow" } ].each do |change|
      put api_v1_transaction_url(transfer.outflow_transaction), params: { transaction: change }, headers: api_headers(@api_key)

      assert_response :unprocessable_entity, change.inspect
      assert_equal 100, outflow.reload.amount, change.inspect
      assert_equal(-100, inflow.reload.amount, change.inspect)
    end

    put api_v1_transaction_url(transfer.outflow_transaction), params: { transaction: { nature: "outflow", notes: "Rent" } }, headers: api_headers(@api_key)
    assert_response :success
    assert_equal "Rent", outflow.reload.notes
  end

  test "create and update refuse a nature outside the documented values" do
    entry = create_transaction(account: @account, amount: 40, name: "Bad nature")

    [ "inlfow", 1, true ].each do |nature|
      put api_v1_transaction_url(entry.transaction), params: { transaction: { nature: nature } }, headers: api_headers(@api_key), as: :json

      assert_response :unprocessable_entity, nature.inspect
      assert_equal 40, entry.reload.amount, nature.inspect

      assert_no_difference("@account.entries.count", nature.inspect) do
        post api_v1_transactions_url,
             params: { transaction: { account_id: @account.id, name: "Bad", amount: 5, date: Date.current, nature: nature } },
             headers: api_headers(@api_key), as: :json
      end
      assert_response :unprocessable_entity, nature.inspect
    end
  end

  test "should not sync the account when only notes change" do
    assert_no_enqueued_jobs only: SyncJob do
      put api_v1_transaction_url(@transaction),
          params: { transaction: { notes: "Just a note" } },
          headers: api_headers(@api_key)
    end
    assert_response :success
  end

  test "should sync the account when the amount changes" do
    assert_enqueued_with(job: SyncJob) do
      put api_v1_transaction_url(@transaction),
          params: { transaction: { amount: 42.00 } },
          headers: api_headers(@api_key)
    end
    assert_response :success
  end

  test "should sync the account when notes and amount change together" do
    assert_enqueued_with(job: SyncJob) do
      put api_v1_transaction_url(@transaction),
          params: { transaction: { notes: "Just a note", amount: 42.00 } },
          headers: api_headers(@api_key)
    end
    assert_response :success
  end

  test "should protect transaction from provider sync when updated with user_modified true" do
    update_params = {
      transaction: {
        name: "Client-owned Name",
        user_modified: true
      }
    }

    put api_v1_transaction_url(@transaction),
        params: update_params,
        headers: api_headers(@api_key)
    assert_response :success

    response_data = JSON.parse(response.body)
    assert_equal "Client-owned Name", response_data["name"]
    assert_equal true, response_data["user_modified"]

    entry = @transaction.entry.reload
    assert entry.user_modified?
    assert entry.protected_from_sync?
  end

  test "date changed via API survives the next provider sync without user_modified" do
    entry = Account::ProviderImportAdapter.new(@account).import_transaction(
      external_id: "plaid_api_date_edit",
      amount: 42.00,
      currency: "USD",
      date: Date.current - 5.days,
      name: "Card payment",
      source: "plaid"
    )

    put api_v1_transaction_url(entry.transaction),
        params: { transaction: { date: (Date.current - 2.days).to_s } },
        headers: api_headers(@api_key)
    assert_response :success
    assert_not entry.reload.user_modified?

    Account::ProviderImportAdapter.new(@account).import_transaction(
      external_id: "plaid_api_date_edit",
      amount: 42.00,
      currency: "USD",
      date: Date.current - 5.days,
      name: "Card payment",
      source: "plaid"
    )

    assert_equal Date.current - 2.days, entry.reload.date
  end

  test "should not change user_modified on update by default" do
    put api_v1_transaction_url(@transaction),
        params: { transaction: { name: "Updated Name Only" } },
        headers: api_headers(@api_key)
    assert_response :success

    assert_equal false, JSON.parse(response.body)["user_modified"]
    assert_not @transaction.entry.reload.user_modified?
  end

  test "should reject update with read-only API key" do
    update_params = {
      transaction: {
        name: "Updated Transaction Name"
      }
    }

    put api_v1_transaction_url(@transaction),
        params: update_params,
        headers: api_headers(@read_only_api_key)
    assert_response :forbidden
  end

  test "should reject update for non-existent transaction" do
    put api_v1_transaction_url(999999),
        params: { transaction: { name: "Test" } },
        headers: api_headers(@api_key)
    assert_response :not_found
  end

  test "should reject update without API key" do
    put api_v1_transaction_url(@transaction), params: { transaction: { name: "Test" } }
    assert_response :unauthorized
  end

  test "should preserve tags when tag_ids not provided in update" do
    # Set up transaction with existing tags
    original_tags = [ Tag.first, Tag.second ]
    @transaction.tags = original_tags
    @transaction.save!

    # Update only the name, without providing tag_ids
    update_params = {
      transaction: {
        name: "Updated Name Only"
      }
    }

    put api_v1_transaction_url(@transaction),
        params: update_params,
        headers: api_headers(@api_key)
    assert_response :success

    @transaction.reload
    assert_equal "Updated Name Only", @transaction.entry.name
    # Tags should be preserved since tag_ids was not in the request
    assert_equal original_tags.map(&:id).sort, @transaction.tag_ids.sort
  end

  # Tags belong to a family: another family's tag id is never linked.
  test "update with another family's tag id is refused and leaves the tags unchanged" do
    own_tag = @family.tags.first
    @transaction.update!(tag_ids: [ own_tag.id ])
    foreign_tag = families(:empty).tags.create!(name: "Foreign", color: "#e99537")

    assert_no_difference -> { Tagging.where(tag_id: foreign_tag.id).count } do
      put api_v1_transaction_url(@transaction),
          params: { transaction: { tag_ids: [ own_tag.id, foreign_tag.id ] } },
          headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
    assert_equal [ own_tag.id ], @transaction.reload.tag_ids
  end

  test "update with a tag id no family owns is refused and leaves the tags unchanged" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids.sort

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ SecureRandom.uuid ] } },
        headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_equal before_ids, @transaction.reload.tag_ids.sort
  end

  test "create with another family's tag id is refused and creates nothing" do
    foreign_tag = families(:empty).tags.create!(name: "Foreign", color: "#e99537")

    assert_no_difference [ "@account.entries.count", "Tagging.count" ] do
      post api_v1_transactions_url,
           params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,
                                    currency: "USD", nature: "expense", tag_ids: [ foreign_tag.id ] } },
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
  end

  test "update with the family's own tags still assigns them" do
    tags = @family.tags.limit(2).to_a
    @transaction.update!(tag_ids: [])

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: tags.map(&:id) } },
        headers: api_headers(@api_key)

    assert_response :success
    assert_equal tags.map(&:id).sort, @transaction.reload.tag_ids.sort
  end

  # One tag named in two spellings is one tag: Postgres matches a UUID in any
  # case, so counting raw strings would call it unknown.
  test "create with one tag spelled in two cases tags it once" do
    tag = @family.tags.first

    assert_difference "Tagging.count", 1 do
      post api_v1_transactions_url,
           params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,
                                    currency: "USD", nature: "expense", tag_ids: [ tag.id, tag.id.upcase ] } },
           headers: api_headers(@api_key)
    end

    assert_response :success
  end

  test "update with one tag spelled in two cases assigns it once" do
    tag = @family.tags.first
    @transaction.update!(tag_ids: [])

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ tag.id, tag.id.upcase ] } },
        headers: api_headers(@api_key)

    assert_response :success
    assert_equal [ tag.id ], @transaction.reload.tag_ids
  end

  test "update with a tag id that is not a UUID is refused and changes nothing" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ @family.tags.first.id, "not-a-uuid" ] } },
        headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_equal before_ids, @transaction.reload.tag_ids
  end

  # With only invalid ids the cast list is [nil], which is not "any?", and the
  # collection writer drops the nil, so this would clear every tag.
  test "update with only ids that are not UUIDs is refused and keeps the tags" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ "not-a-uuid" ] } },
        headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_equal before_ids, @transaction.reload.tag_ids
  end

  test "create with only ids that are not UUIDs is refused and creates nothing" do
    assert_no_difference [ "@account.entries.count", "Tagging.count" ] do
      post api_v1_transactions_url,
           params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,
                                    currency: "USD", nature: "expense", tag_ids: [ "not-a-uuid" ] } },
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
  end

  # Strong parameters drops a tag_ids of any other shape, which would otherwise
  # read as "no tags" and clear them.
  [
    [ "an array holding a hash", ->(id) { [ id, {} ] } ],
    [ "an array holding a false", ->(id) { [ id, false ] } ],
    [ "a bare string", ->(id) { id } ],
    [ "a hash", ->(id) { { id: id } } ]
  ].each do |shape, build|
    test "update with #{shape} as tag_ids is refused and changes nothing" do
      own_tag = @family.tags.first
      @transaction.update!(tag_ids: [ own_tag.id ])
      name_before = @transaction.entry.reload.name

      put api_v1_transaction_url(@transaction),
          params: { transaction: { name: "Renamed", tag_ids: build.call(own_tag.id) } },
          headers: api_headers(@api_key),
          as: :json

      assert_response :unprocessable_entity
      assert_equal "validation_failed", JSON.parse(response.body)["error"]
      assert_equal [ own_tag.id ], @transaction.reload.tag_ids
      assert_equal name_before, @transaction.entry.reload.name
    end

    test "create with #{shape} as tag_ids is refused and creates nothing" do
      assert_no_difference -> { Entry.count } do
        post api_v1_transactions_url,
             params: { transaction: { account_id: @account.id, name: "Refused", amount: 10, date: Date.current,
                                      currency: "USD", nature: "expense", tag_ids: build.call(@family.tags.first.id) } },
             headers: api_headers(@api_key),
             as: :json
      end

      assert_response :unprocessable_entity
      assert_equal "validation_failed", JSON.parse(response.body)["error"]
    end
  end

  [ [ "an empty array", [] ], [ "a null", nil ], [ "a blank entry", [ "" ] ] ].each do |shape, value|
    test "update with #{shape} as tag_ids still clears the tags" do
      @transaction.update!(tag_ids: [ @family.tags.first.id ])

      put api_v1_transaction_url(@transaction),
          params: { transaction: { tag_ids: value } },
          headers: api_headers(@api_key),
          as: :json

      assert_response :success
      assert_empty @transaction.reload.tag_ids
    end
  end

  # Categories and merchants are used through the family: another family's id
  # is never linked.
  test "update with another family's category is refused and changes nothing" do
    own_category = @family.categories.first
    @transaction.update!(category: own_category)
    name_before = @transaction.entry.reload.name

    put api_v1_transaction_url(@transaction),
        params: { transaction: { name: "Renamed", category_id: foreign_category.id } },
        headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
    assert_equal own_category.id, @transaction.reload.category_id
    assert_equal name_before, @transaction.entry.reload.name
  end

  test "update with another family's merchant is refused and changes nothing" do
    own_merchant = @family.merchants.create!(name: "Own Merchant")
    @transaction.update!(merchant: own_merchant)
    name_before = @transaction.entry.reload.name

    put api_v1_transaction_url(@transaction),
        params: { transaction: { name: "Renamed", merchant_id: foreign_merchant.id } },
        headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
    assert_equal own_merchant.id, @transaction.reload.merchant_id
    assert_equal name_before, @transaction.entry.reload.name
  end

  %w[category_id merchant_id].each do |attribute|
    test "update with a #{attribute} that does not exist is refused" do
      assert_no_changes -> { @transaction.reload.public_send(attribute) } do
        put api_v1_transaction_url(@transaction),
            params: { transaction: { attribute => SecureRandom.uuid } },
            headers: api_headers(@api_key)
      end

      assert_response :unprocessable_entity
    end

    test "create with a #{attribute} that does not exist is refused and creates nothing" do
      assert_no_difference -> { Entry.count } do
        post api_v1_transactions_url,
             params: { transaction: reference_create_params(attribute => SecureRandom.uuid) },
             headers: api_headers(@api_key)
      end

      assert_response :unprocessable_entity
    end

    test "update with #{attribute} omitted or blank keeps its value" do
      own = { "category_id" => @family.categories.first.id,
              "merchant_id" => @family.merchants.create!(name: "Kept Merchant").id }.fetch(attribute)
      @transaction.update!(attribute => own)

      [ { name: "Omitted" }, { name: "Blank", attribute => "" } ].each do |fields|
        put api_v1_transaction_url(@transaction),
            params: { transaction: fields },
            headers: api_headers(@api_key)

        assert_response :success
        assert_equal fields[:name], @transaction.entry.reload.name
        assert_equal own, @transaction.reload.public_send(attribute)
      end
    end
  end

  test "create with another family's category is refused and creates nothing" do
    assert_no_difference -> { Entry.count } do
      post api_v1_transactions_url,
           params: { transaction: reference_create_params(category_id: foreign_category.id) },
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
  end

  test "create with another family's merchant is refused and creates nothing" do
    assert_no_difference -> { Entry.count } do
      post api_v1_transactions_url,
           params: { transaction: reference_create_params(merchant_id: foreign_merchant.id) },
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
  end

  test "create and update still assign the family's own category and merchant" do
    category = @family.categories.first
    merchant = @family.merchants.create!(name: "Assigned Merchant")

    post api_v1_transactions_url,
         params: { transaction: reference_create_params(category_id: category.id, merchant_id: merchant.id) },
         headers: api_headers(@api_key)

    assert_response :created
    created = Transaction.find(JSON.parse(response.body)["id"])
    assert_equal category.id, created.category_id
    assert_equal merchant.id, created.merchant_id

    @transaction.update!(category: nil, merchant: nil)

    put api_v1_transaction_url(@transaction),
        params: { transaction: { category_id: category.id, merchant_id: merchant.id } },
        headers: api_headers(@api_key)

    assert_response :success
    assert_equal category.id, @transaction.reload.category_id
    assert_equal merchant.id, @transaction.merchant_id
  end

  test "a provider merchant the user can reach still assigns, and one they cannot is refused" do
    reachable = ProviderMerchant.create!(name: "Reachable Provider", source: "plaid")
    unreachable = ProviderMerchant.create!(name: "Unreachable Provider", source: "plaid")
    other_transaction = @family.transactions.where.not(id: @transaction.id).first
    other_transaction.update!(merchant: reachable)
    @transaction.update!(merchant: nil)

    put api_v1_transaction_url(@transaction),
        params: { transaction: { merchant_id: unreachable.id } },
        headers: api_headers(@api_key)
    assert_response :unprocessable_entity
    assert_nil @transaction.reload.merchant_id

    put api_v1_transaction_url(@transaction),
        params: { transaction: { merchant_id: reachable.id } },
        headers: api_headers(@api_key)
    assert_response :success
    assert_equal reachable.id, @transaction.reload.merchant_id

    post api_v1_transactions_url,
         params: { transaction: reference_create_params(merchant_id: reachable.id) },
         headers: api_headers(@api_key)
    assert_response :created
    assert_equal reachable.id, Transaction.find(JSON.parse(response.body)["id"]).merchant_id
  end

  # A client re-sends the ids it read back, so a row already holding a foreign
  # category must stay editable. No new link is made.
  test "update re-sending a foreign category the transaction already holds still saves" do
    @transaction.update_columns(category_id: foreign_category.id)

    put api_v1_transaction_url(@transaction),
        params: { transaction: { name: "Still editable", category_id: foreign_category.id } },
        headers: api_headers(@api_key)

    assert_response :success
    assert_equal "Still editable", @transaction.entry.reload.name
  end

  test "update re-sending a held foreign category or merchant in upper case still saves" do
    @transaction.update_columns(category_id: foreign_category.id, merchant_id: foreign_merchant.id)

    put api_v1_transaction_url(@transaction),
        params: { transaction: { name: "Still editable", category_id: foreign_category.id.upcase,
                                 merchant_id: foreign_merchant.id.upcase } },
        headers: api_headers(@api_key)

    assert_response :success
    assert_equal "Still editable", @transaction.entry.reload.name
  end

  test "a category or merchant id that is not a UUID is refused" do
    { category_id: "not-a-uuid", merchant_id: "not-a-uuid" }.each do |key, value|
      put api_v1_transaction_url(@transaction),
          params: { transaction: { name: "Renamed", key => value } },
          headers: api_headers(@api_key)

      assert_response :unprocessable_entity, "#{key} was accepted"
    end
    assert_not_equal "Renamed", @transaction.entry.reload.name
  end

  test "update re-sending a foreign merchant the transaction already holds still saves" do
    @transaction.update_columns(merchant_id: foreign_merchant.id)

    put api_v1_transaction_url(@transaction),
        params: { transaction: { name: "Still editable", merchant_id: foreign_merchant.id } },
        headers: api_headers(@api_key)

    assert_response :success
    assert_equal "Still editable", @transaction.entry.reload.name
  end

  test "a foreign merchant already on one transaction cannot be linked to another" do
    holder = @family.transactions.where.not(id: @transaction.id).first
    holder.update_columns(merchant_id: foreign_merchant.id)
    @transaction.update!(merchant: nil)

    put api_v1_transaction_url(@transaction),
        params: { transaction: { merchant_id: foreign_merchant.id } },
        headers: api_headers(@api_key)
    assert_response :unprocessable_entity
    assert_nil @transaction.reload.merchant_id

    assert_no_difference -> { Entry.count } do
      post api_v1_transactions_url,
           params: { transaction: reference_create_params(merchant_id: foreign_merchant.id) },
           headers: api_headers(@api_key)
    end
    assert_response :unprocessable_entity
  end

  test "should store a repeated tag id once in update" do
    tag = @family.tags.first

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ tag.id, tag.id ] } },
        headers: api_headers(@api_key)
    assert_response :success

    assert_equal [ tag.id ], @transaction.reload.taggings.pluck(:tag_id)
  end

  test "update with a malformed tag id leaves the tags unchanged" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids.sort

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ "not-a-uuid" ] } },
        headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
    assert_equal before_ids, @transaction.reload.tag_ids.sort
  end

  test "create with a malformed tag id is refused and creates nothing" do
    assert_no_difference("@account.entries.count") do
      post api_v1_transactions_url,
           params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,
                                    currency: "USD", nature: "expense", tag_ids: [ "not-a-uuid" ] } },
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
  end

  # Strong parameters drop a scalar where a list is permitted, so a check made
  # after `permit` saw no tags, and the update cleared every tag it held.
  test "update with a scalar tag id leaves the tags unchanged" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids.sort

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: "not-a-uuid" } },
        headers: api_headers(@api_key)

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
    assert_equal before_ids, @transaction.reload.tag_ids.sort
  end

  test "update with a tag id that is not a string leaves the tags unchanged" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids.sort

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ { id: @family.tags.first.id } ] } }.to_json,
        headers: api_headers(@api_key).merge("Content-Type" => "application/json")

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
    assert_equal before_ids, @transaction.reload.tag_ids.sort
  end

  # `compact_blank` would drop an empty object or `false` before the check,
  # and then `permit` drops the whole list, or the id writer drops `false`:
  # either way the tags were cleared.
  test "update with a blank non-string tag id leaves the tags unchanged" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids.sort

    [ [ @family.tags.first.id, {} ], [ false ] ].each do |tag_ids|
      put api_v1_transaction_url(@transaction),
          params: { transaction: { tag_ids: tag_ids } }.to_json,
          headers: api_headers(@api_key).merge("Content-Type" => "application/json")

      assert_response :unprocessable_entity, "tag_ids: #{tag_ids.inspect}"
      assert_equal "validation_failed", JSON.parse(response.body)["error"], "tag_ids: #{tag_ids.inspect}"
      assert_equal before_ids, @transaction.reload.tag_ids.sort, "tag_ids: #{tag_ids.inspect}"
    end
  end

  test "update with an object for its tag ids leaves the tags unchanged" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])
    before_ids = @transaction.reload.tag_ids.sort

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: {} } }.to_json,
        headers: api_headers(@api_key).merge("Content-Type" => "application/json")

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
    assert_equal before_ids, @transaction.reload.tag_ids.sort
  end

  test "create with a scalar tag id is refused and creates nothing" do
    assert_no_difference("@account.entries.count") do
      post api_v1_transactions_url,
           params: { transaction: { account_id: @account.id, name: "Tagged", amount: 25.00, date: Date.current,
                                    currency: "USD", nature: "expense", tag_ids: "not-a-uuid" } },
           headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
  end

  test "update with a blank tag id list still clears the tags" do
    @transaction.update!(tag_ids: [ @family.tags.first.id ])

    put api_v1_transaction_url(@transaction),
        params: { transaction: { tag_ids: [ "" ] } },
        headers: api_headers(@api_key)

    assert_response :success
    assert_empty @transaction.reload.tag_ids
  end

  test "should clear tags when empty tag_ids explicitly provided in update" do
    # Set up transaction with existing tags
    @transaction.tags = [ Tag.first, Tag.second ]
    @transaction.save!

    # Explicitly provide empty tag_ids to clear tags
    update_params = {
      transaction: {
        name: "Updated Name",
        tag_ids: []
      }
    }

    put api_v1_transaction_url(@transaction),
        params: update_params,
        headers: api_headers(@api_key)
    assert_response :success

    @transaction.reload
    # Tags should be cleared since tag_ids was explicitly provided as empty
    assert_empty @transaction.tags
  end

  test "should update tags when tag_ids explicitly provided in update" do
    # Set up transaction with one tag
    @transaction.tags = [ Tag.first ]
    @transaction.save!

    new_tags = [ Tag.second ]

    update_params = {
      transaction: {
        tag_ids: new_tags.map(&:id)
      }
    }

    put api_v1_transaction_url(@transaction),
        params: update_params,
        headers: api_headers(@api_key)
    assert_response :success

    @transaction.reload
    assert_equal new_tags.map(&:id), @transaction.tag_ids
  end

  # DESTROY action tests
  test "should destroy transaction" do
  entry_to_delete = @account.entries.create!(
    name: "Transaction to Delete",
    amount: 10.00,
    currency: "USD",
    date: Date.current,
    entryable: Transaction.new
  )
  transaction_to_delete = entry_to_delete.transaction

  assert_difference("@account.entries.count", -1) do
    delete api_v1_transaction_url(transaction_to_delete), headers: api_headers(@api_key)
  end

  assert_response :success
  response_data = JSON.parse(response.body)
  assert response_data.key?("message")
end

  test "should reject destroying a split whose part is linked as a transfer" do
    parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")
    part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first
    link_split_part_to_loan(part)

    assert_no_difference [ "Entry.count", "Transfer.count" ] do
      delete api_v1_transaction_url(parent.transaction), headers: api_headers(@api_key)
    end

    assert_response :unprocessable_entity
    assert_equal "validation_failed", JSON.parse(response.body)["error"]
  end

  test "should reject destroy with read-only API key" do
    delete api_v1_transaction_url(@transaction), headers: api_headers(@read_only_api_key)
    assert_response :forbidden
  end

  test "should reject destroy for non-existent transaction" do
    delete api_v1_transaction_url(999999), headers: api_headers(@api_key)
    assert_response :not_found
  end

  test "should reject destroy without API key" do
    delete api_v1_transaction_url(@transaction)
    assert_response :unauthorized
  end

  # Shared-account permission tests
  test "a member with read-only access can read but not change or delete a shared transaction" do
    key, entry = shared_member_key_and_entry("read_only")

    get api_v1_transaction_url(entry.transaction), headers: api_headers(key)
    assert_response :success

    patch api_v1_transaction_url(entry.transaction), params: { transaction: { notes: "hi" } }, headers: api_headers(key)
    assert_response :forbidden
    assert_nil entry.reload.notes

    assert_no_difference "Entry.count" do
      delete api_v1_transaction_url(entry.transaction), headers: api_headers(key)
    end
    assert_response :forbidden
    assert_equal "You do not have permission to delete this transaction", JSON.parse(response.body)["message"]
  end

  test "a read_write member can annotate but not change financial fields or delete" do
    key, entry = shared_member_key_and_entry("read_write")

    patch api_v1_transaction_url(entry.transaction), params: { transaction: { notes: "annotated" } }, headers: api_headers(key)
    assert_response :success
    assert_equal "annotated", entry.reload.notes

    [ { amount: 999 }, { name: "Renamed" }, { date: 3.days.ago.to_date }, { notes: "x", amount: 999 } ].each do |attrs|
      patch api_v1_transaction_url(entry.transaction), params: { transaction: attrs }, headers: api_headers(key)
      assert_response :forbidden, "expected #{attrs.keys} to be refused"
    end
    assert_equal "annotated", entry.reload.notes
    assert_equal 42, entry.amount

    assert_no_difference "Entry.count" do
      delete api_v1_transaction_url(entry.transaction), headers: api_headers(key)
    end
    assert_response :forbidden
  end

  test "a read_write member can change category, merchant and tags" do
    key, entry = shared_member_key_and_entry("read_write")
    category = @user.family.categories.first
    merchant = @user.family.merchants.first || FamilyMerchant.create!(family: @user.family, name: "Shared Cafe")
    tag = @user.family.tags.first || @user.family.tags.create!(name: "shared-tag")

    patch api_v1_transaction_url(entry.transaction),
          params: { transaction: { category_id: category.id, merchant_id: merchant.id, tag_ids: [ tag.id ] } },
          headers: api_headers(key)

    assert_response :success
    transaction = entry.transaction.reload
    assert_equal category.id, transaction.category_id
    assert_equal merchant.id, transaction.merchant_id
    assert_equal [ tag.id ], transaction.tag_ids
  end

  test "a read_write member cannot change description or user_modified" do
    key, entry = shared_member_key_and_entry("read_write")

    [ { description: "Renamed" }, { user_modified: true } ].each do |attrs|
      patch api_v1_transaction_url(entry.transaction), params: { transaction: attrs }, headers: api_headers(key)
      assert_response :forbidden, "expected #{attrs.keys} to be refused"
      assert_equal "forbidden", JSON.parse(response.body)["error"]
      assert_equal "You do not have permission to change this transaction", JSON.parse(response.body)["message"]
    end
    assert_equal "Shared txn", entry.reload.name
  end

  test "unpermitted keys are ignored for a read_write member, account_id included" do
    key, entry = shared_member_key_and_entry("read_write")
    other = @user.family.accounts.create!(name: "Other", owner: @user, balance: 0, currency: "USD", accountable: Depository.new)

    patch api_v1_transaction_url(entry.transaction),
          params: { transaction: { notes: "kept", account_id: other.id } },
          headers: api_headers(key)

    assert_response :success
    entry.reload
    assert_equal "kept", entry.notes
    assert_not_equal other.id, entry.account_id
  end

  test "a full_control member can change and delete a shared transaction" do
    key, entry = shared_member_key_and_entry("full_control")

    patch api_v1_transaction_url(entry.transaction), params: { transaction: { name: "Renamed" } }, headers: api_headers(key)
    assert_response :success
    assert_equal "Renamed", entry.reload.name

    assert_difference "Entry.count", -1 do
      delete api_v1_transaction_url(entry.transaction), headers: api_headers(key)
    end
    assert_response :success
  end

  # JSON structure tests
  test "transaction JSON should have expected structure" do
    get api_v1_transaction_url(@transaction), headers: api_headers(@api_key)
    assert_response :success

    transaction_data = JSON.parse(response.body)

    # Basic fields
    assert transaction_data.key?("id")
    assert transaction_data.key?("date")
    assert transaction_data.key?("amount")
    assert transaction_data.key?("currency")
    assert transaction_data.key?("name")
    assert transaction_data.key?("classification")
    assert transaction_data.key?("created_at")
    assert transaction_data.key?("updated_at")

    # Account information
    assert transaction_data.key?("account")
    assert transaction_data["account"].key?("id")
    assert transaction_data["account"].key?("name")
    assert transaction_data["account"].key?("account_type")

    # Optional fields should be present (even if nil)
    assert transaction_data.key?("category")
    assert transaction_data.key?("merchant")
    assert transaction_data.key?("tags")
    assert transaction_data.key?("transfer")
    assert transaction_data.key?("notes")
  end

  test "transactions with transfers should include transfer information" do
    transfer = create_transfer_between_accounts

    get api_v1_transaction_url(transfer.inflow_transaction), headers: api_headers(@api_key)
    assert_response :success

    transaction_data = JSON.parse(response.body)
    assert_not_nil transaction_data["transfer"]
    assert transaction_data["transfer"].key?("id")
    assert transaction_data["transfer"].key?("amount")
    assert transaction_data["transfer"].key?("currency")
    assert transaction_data["transfer"].key?("other_account")
  end

  test "index renders transfer rows without per-transfer transaction lookups" do
    transfer = create_transfer_between_accounts

    queries = capture_sql_queries do
      get api_v1_transactions_url,
          params: { per_page: 100 },
          headers: api_headers(@api_key)
    end

    assert_response :success

    response_data = JSON.parse(response.body)
    transfer_transaction_ids = [ transfer.inflow_transaction_id, transfer.outflow_transaction_id ]
    transfer_rows = response_data["transactions"].select { |transaction| transfer_transaction_ids.include?(transaction["id"]) }

    assert_equal 2, transfer_rows.size
    assert transfer_rows.all? { |transaction| transaction["transfer"].present? }
    assert_empty queries.grep(/SELECT "transactions"\.\* FROM "transactions" WHERE "transactions"\."id" =/)
    assert_empty queries.grep(/SELECT "entries"\.\* FROM "entries" WHERE "entries"\."id" =/)
    assert_empty queries.grep(/SELECT "accounts"\.\* FROM "accounts" WHERE "accounts"\."id" =/)
  end

  test "transaction JSON exposes the exact stored amount alongside the rounded ones" do
    entry = create_transaction(account: @account, amount: 12.3456, name: "Four decimals")

    get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)
    assert_response :success

    data = JSON.parse(response.body)
    assert_equal "12.3456", data["amount_decimal"]
    assert_equal 1235, data["amount_cents"], "amount_cents stays display-rounded"
    assert_amount_cents_fields(data)
  end

  test "amount_decimal keeps the stored sign and ignores the request locale" do
    entry = create_transaction(account: @account, amount: -1234.5, name: "Refund")

    get api_v1_transaction_url(entry.transaction),
        headers: api_headers(@api_key).merge("Accept-Language" => "de")
    assert_response :success

    assert_equal "-1234.5", JSON.parse(response.body)["amount_decimal"]
  end

  test "transaction JSON exposes kind" do
    entry = create_transaction(account: @account, amount: -250, name: "Loan payment", kind: "loan_payment")

    get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)
    assert_response :success

    data = JSON.parse(response.body)
    assert_equal "loan_payment", data["kind"]
    assert_equal "income", data["classification"], "classification still follows the amount sign; kind lets a client tell"
  end

  test "an ordinary transaction is neither a split parent nor excluded" do
    entry = create_transaction(account: @account, amount: 40, name: "Plain")

    get api_v1_transaction_url(entry.transaction), headers: api_headers(@api_key)
    assert_response :success

    data = JSON.parse(response.body)
    assert_equal "standard", data["kind"]
    assert_equal false, data["split_parent"]
    assert_equal false, data["excluded"]
  end

  test "index marks split parents and their children" do
    parent = create_transaction(account: @account, amount: 100, name: "Split parent", date: 3.days.ago.to_date)
    parent.split!([
      { name: "Kept", amount: 60, category_id: nil },
      { name: "Left out", amount: 40, category_id: nil, excluded: true }
    ])

    get api_v1_transactions_url,
        params: { account_id: @account.id, start_date: 3.days.ago.to_date, end_date: 3.days.ago.to_date, per_page: 100 },
        headers: api_headers(@api_key)
    assert_response :success

    rows = JSON.parse(response.body)["transactions"].index_by { |row| row["name"] }
    assert_equal true, rows["Split parent"]["split_parent"]
    assert_equal true, rows["Split parent"]["excluded"]
    assert_equal false, rows["Kept"]["split_parent"]
    assert_equal false, rows["Kept"]["excluded"]
    assert_equal false, rows["Left out"]["split_parent"]
    assert_equal true, rows["Left out"]["excluded"]

    # show renders the same partial without the batched ids and must still report it
    get api_v1_transaction_url(parent.transaction), headers: api_headers(@api_key)
    assert_response :success
    assert_equal true, JSON.parse(response.body)["split_parent"]
  end

  test "index works out split_parent without a query per row" do
    split_parent = lambda do |name|
      create_transaction(account: @account, amount: 10, name: name).split!([
        { name: "#{name} a", amount: 4, category_id: nil },
        { name: "#{name} b", amount: 6, category_id: nil }
      ])
    end

    split_parent.call("Baseline")
    baseline_queries = count_db_queries do
      get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)
      assert_response :success
    end

    3.times { |i| split_parent.call("More #{i}") }
    expanded_queries = count_db_queries do
      get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)
      assert_response :success
    end

    assert_equal baseline_queries, expanded_queries
  end

  test "index works out split_parent without loading the split children" do
    create_transaction(account: @account, amount: 10, name: "Big split").split!(
      [ { name: "Part a", amount: 4, category_id: nil }, { name: "Part b", amount: 6, category_id: nil } ]
    )

    queries = capture_sql_queries do
      get api_v1_transactions_url, params: { per_page: 100 }, headers: api_headers(@api_key)
    end
    assert_response :success

    assert_empty queries.grep(/SELECT "entries"\.\* FROM "entries" WHERE "entries"\."parent_entry_id"/),
                 "split children should not be loaded just to compute split_parent"
  end

  test "show exposes the activity label and the safe provider fields, not the raw extra" do
    security = Security.create!(ticker: "WHT#{SecureRandom.hex(2).upcase}", name: "Withholding Security", country_code: "US")
    entry = create_transaction(
      account: @account,
      amount: 1.5,
      name: "Withholding Tax for WHT",
      currency: "EUR",
      source: "ibkr",
      external_id: "ibkr_cash_#{SecureRandom.hex(4)}",
      entryable: Transaction.new(
        investment_activity_label: "Dividend",
        extra: {
          "exchange_rate" => 0.9215,
          "security_id" => security.id,
          "ibkr" => { "type" => "Withholding Tax", "conid" => "CONID-SECRET-1", "account_id" => "U7654321" }
        }
      )
    )

    get api_v1_transaction_url(entry.entryable), headers: api_headers(@read_only_api_key)
    assert_response :success

    body = JSON.parse(response.body)
    assert_equal "Dividend", body["investment_activity_label"]
    assert_equal "Withholding Tax", body["provider_type"]
    assert_equal security.id, body["security_id"]
    assert_equal 0.9215, body["exchange_rate"]
    assert_equal "EUR", body["amount_currency"]
    assert_not body.key?("extra")
    assert_not_includes response.body, "CONID-SECRET-1"
    assert_not_includes response.body, "U7654321"
  end

  test "index returns null tax fields for a plain transaction and ignores a provider payload that is not a hash" do
    entry = create_transaction(
      account: @account,
      name: "Plain row",
      source: "plaid",
      entryable: Transaction.new
    )
    # Written past validation, as a provider writing extra directly might.
    entry.entryable.update_column(:extra, { "plaid" => "raw-string-payload", "security" => "raw-string-security", "exchange_rate" => "not-a-number" })

    get api_v1_transactions_url, params: { account_id: @account.id, per_page: 100 }, headers: api_headers(@read_only_api_key)
    assert_response :success

    txn_json = JSON.parse(response.body)["transactions"].find { |txn| txn["id"] == entry.entryable.id }
    assert txn_json
    %w[investment_activity_label provider_type security_id exchange_rate].each do |field|
      assert txn_json.key?(field), "expected #{field} in the response"
      assert_nil txn_json[field], "expected #{field} to be null"
    end
    assert_not_includes response.body, "raw-string-payload"
    assert_not_includes response.body, "raw-string-security"
  end

  test "show and index return null tax fields instead of failing when extra is not a hash" do
    entry = create_transaction(account: @account, name: "Malformed extra row", source: "ibkr", currency: "EUR", entryable: Transaction.new)
    transaction = entry.entryable

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

      get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)
      assert_response :success, "show failed for extra = #{malformed.inspect}"
      body = JSON.parse(response.body)

      get api_v1_transactions_url, params: { account_id: @account.id, per_page: 100 }, headers: api_headers(@read_only_api_key)
      assert_response :success, "index failed for extra = #{malformed.inspect}"
      txn_json = JSON.parse(response.body)["transactions"].find { |row| row["id"] == transaction.id }
      assert txn_json

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

  test "security_id is only a uuid string, never other data stored under the key" do
    entry = create_transaction(account: @account, name: "Odd security id", currency: "EUR", entryable: Transaction.new)
    transaction = entry.entryable

    [ { "account_number" => "U9999999" }, 12345, "not-a-uuid", [ "U9999999" ] ].each do |stored|
      transaction.update_column(:extra, { "security_id" => stored })

      get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)
      assert_response :success
      assert_nil JSON.parse(response.body)["security_id"], "expected null for security_id = #{stored.inspect}"
      assert_not_includes response.body, "U9999999"
    end
  end

  # A stored decimal can be positive and finite yet become 0.0 or Infinity
  # as a Float, which is what the response carries.
  test "exchange rate is null when the stored value does not fit a Float" do
    entry = create_transaction(account: @account, name: "Float range row", currency: "EUR", entryable: Transaction.new)
    transaction = entry.entryable

    [ "1e-400", "1e400" ].each do |stored|
      transaction.update_column(:extra, { "exchange_rate" => stored })
      get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)
      assert_response :success
      assert_nil JSON.parse(response.body)["exchange_rate"], stored
      assert_nil transaction.reload.numeric_exchange_rate, stored
    end
  end

  test "exchange rate compares currency codes regardless of case" do
    entry = create_transaction(account: @account, name: "Lower case row", currency: "EUR", entryable: Transaction.new)
    entry.update_column(:currency, @account.currency.downcase)
    entry.entryable.update_column(:extra, { "exchange_rate" => 1.1 })

    get api_v1_transaction_url(entry.entryable), headers: api_headers(@read_only_api_key)
    assert_response :success
    assert_nil JSON.parse(response.body)["exchange_rate"]
  end

  test "exchange rate is read the way the app converts it and only where it applies" do
    entry = create_transaction(account: @account, name: "Rate row", currency: "EUR", entryable: Transaction.new)
    transaction = entry.entryable

    # Float() would read "0x10" as 16; the app's to_d reads it as 0 and
    # refuses to convert with it.
    transaction.update_column(:extra, { "exchange_rate" => "0x10" })
    get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)
    assert_response :success
    assert_nil JSON.parse(response.body)["exchange_rate"]

    # A row in the account's own currency is never converted, so a stored rate
    # on it is not exposed.
    entry.update_column(:currency, @account.currency)
    transaction.update_column(:extra, { "exchange_rate" => 1.085 })
    get api_v1_transaction_url(transaction), headers: api_headers(@read_only_api_key)
    assert_nil JSON.parse(response.body)["exchange_rate"]
  end

  private

    def foreign_category
      @foreign_category ||= families(:empty).categories.create!(name: "Foreign", color: "#e99537", lucide_icon: "circle")
    end

    def foreign_merchant
      @foreign_merchant ||= families(:empty).merchants.create!(name: "Foreign")
    end

    def reference_create_params(references)
      { account_id: @account.id, name: "With references", amount: 10, date: Date.current,
        currency: "USD", nature: "expense" }.merge(references)
    end

    def shared_member_key_and_entry(permission)
      member = users(:family_member)
      member.api_keys.active.destroy_all
      key = ApiKey.create!(user: member, name: "Member RW", key: ApiKey.generate_secure_key, scopes: %w[read_write], source: "web")
      Redis.new.del("api_rate_limit:#{key.id}")

      account = member.family.accounts.create!(name: "Admin Shared Checking", owner: @user, balance: 1_000,
                                               currency: "USD", accountable: Depository.new)
      account.account_shares.create!(user: member, permission: permission, include_in_finances: true)
      entry = account.entries.create!(name: "Shared txn", amount: 42, currency: "USD", date: Date.current, entryable: Transaction.new)
      [ key, entry ]
    end

    def api_headers(api_key)
      { "X-Api-Key" => api_key.display_key }
    end

    # Counts every statement, including the ones the query cache answers. The
    # cache hides a preload whose IN list happens to match an earlier one in the
    # same order, and that order follows the rows' physical order, so skipping
    # cached statements made the count change from run to run. It would also
    # hide a repeated per-row query.
    def count_db_queries(&block)
      queries = 0
      callback = lambda do |_name, _started, _finished, _unique_id, payload|
        return if payload[:name].in?(%w[SCHEMA TRANSACTION])

        queries += 1
      end

      ActiveSupport::Notifications.subscribed(callback, "sql.active_record", &block)
      queries
    end

    def create_transfer_between_accounts
      from_account = @family.accounts.create!(
        name: "Transfer From Account",
        balance: 1000,
        currency: "USD",
        accountable: Depository.new
      )

      to_account = @family.accounts.create!(
        name: "Transfer To Account",
        balance: 0,
        currency: "USD",
        accountable: Depository.new
      )

      Transfer::Creator.new(
        family: @family,
        source_account_id: from_account.id,
        destination_account_id: to_account.id,
        date: Date.current,
        amount: 100
      ).create
    end

    def capture_sql_queries
      queries = []
      callback = lambda do |_name, _started, _finished, _unique_id, payload|
        next if payload[:cached]
        next if %w[SCHEMA TRANSACTION].include?(payload[:name])

        queries << payload[:sql].squish
      end

      ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
        yield
      end

      queries
    end

    # Validates agent-friendly numeric fields: type, sign invariants
    def assert_amount_cents_fields(txn_json)
      assert txn_json.key?("amount_cents"), "Expected amount_cents field"
      assert txn_json.key?("signed_amount_cents"), "Expected signed_amount_cents field"
      assert_kind_of Integer, txn_json["amount_cents"]
      assert_kind_of Integer, txn_json["signed_amount_cents"]
      assert_operator txn_json["amount_cents"], :>=, 0, "amount_cents must be non-negative"
      assert_equal txn_json["amount_cents"].abs, txn_json["signed_amount_cents"].abs,
                   "Absolute values of amount_cents and signed_amount_cents must match"
      if txn_json["classification"] == "income"
        assert_operator txn_json["signed_amount_cents"], :>=, 0,
                        "income transactions should have non-negative signed_amount_cents"
      else
        assert_operator txn_json["signed_amount_cents"], :<=, 0,
                        "non-income transactions should have non-positive signed_amount_cents"
      end
    end

    def create_disabled_account_transaction(name:, date: Date.current)
      create_account_transaction(status: "disabled", name: name, date: date)
    end

    def create_account_transaction(status:, name:, date: Date.current)
      account = @family.accounts.create!(
        name: "#{status.titleize} Checking #{SecureRandom.hex(4)}",
        balance: 0,
        currency: "USD",
        status: status,
        accountable: Depository.new
      )

      entry = account.entries.create!(
        name: name,
        amount: 12.34,
        currency: "USD",
        date: date,
        entryable: Transaction.new
      )

      entry.transaction
    end
end