Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
50.0 KB
Raw Blame
require "test_helper"

class TransfersControllerTest < ActionDispatch::IntegrationTest
  include EntriesTestHelper

  setup do
    sign_in users(:family_admin)
  end

  test "should get new" do
    get new_transfer_url
    assert_response :success
  end

  test "excludes disabled accounts from the new transfer form" do
    disabled_account = accounts(:depository)
    disabled_account.update!(status: "disabled")

    get new_transfer_url

    assert_response :success
    assert_no_match disabled_account.name, response.body
  end

  test "can create transfers" do
    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: accounts(:depository).id,
          to_account_id: accounts(:credit_card).id,
          date: Date.current,
          amount: 100,
          name: "Test Transfer"
        }
      }
      assert_enqueued_with job: SyncJob
    end
  end

  test "resubmitting the same idempotency key does not create a duplicate transfer" do
    idempotency_key = SecureRandom.uuid
    params = {
      transfer: {
        from_account_id: accounts(:depository).id,
        to_account_id: accounts(:credit_card).id,
        date: Date.current,
        amount: 100,
        name: "Test Transfer",
        idempotency_key: idempotency_key
      }
    }

    assert_difference "Transfer.count", 1 do
      assert_difference "Entry.count", 2 do
        post transfers_url, params: params
      end
    end
    first_transfer = Transfer.order(:created_at).last

    # Simulates a double-click or a browser retry: same form, same
    # idempotency key, submitted again after the first request already
    # completed and committed.
    assert_no_difference [ "Transfer.count", "Entry.count" ] do
      post transfers_url, params: params
    end
    assert_redirected_to transactions_path
  end

  test "the idempotency key does not mark either leg as provider-linked" do
    # Regression test: the key must not be stored in external_id/source
    # (Entry#linked? = external_id.present?), or an ordinary manual transfer
    # would incorrectly look provider-synced.
    post transfers_url, params: {
      transfer: {
        from_account_id: accounts(:depository).id,
        to_account_id: accounts(:credit_card).id,
        date: Date.current,
        amount: 100,
        name: "Test Transfer",
        source_fee_amount: 3,
        idempotency_key: SecureRandom.uuid
      }
    }

    transfer = Transfer.order(:created_at).last
    [ transfer.outflow_transaction.entry, transfer.inflow_transaction.entry, transfer.fee_transactions.first.entry ].each do |entry|
      assert_not entry.linked?
      assert_nil entry.external_id
      assert_nil entry.source
    end
  end

  test "each leg gets a distinct idempotency key so fee legs don't collide with their primary leg" do
    # Regression test: the outflow/source-fee share source_account, and the
    # inflow/destination-fee share destination_account. The unique index is
    # scoped per account_id, so without role-specific suffixes a fee leg
    # would collide with its primary leg under the same idempotency key.
    post transfers_url, params: {
      transfer: {
        from_account_id: accounts(:depository).id,
        to_account_id: accounts(:credit_card).id,
        date: Date.current,
        amount: 100,
        name: "Test Transfer",
        source_fee_amount: 2,
        destination_fee_amount: 3,
        idempotency_key: SecureRandom.uuid
      }
    }

    transfer = Transfer.order(:created_at).last
    keys = [
      transfer.outflow_transaction.entry.idempotency_key,
      transfer.inflow_transaction.entry.idempotency_key,
      transfer.fee_transactions.map { |t| t.entry.idempotency_key }
    ].flatten

    assert_equal keys.uniq.length, keys.length
    assert keys.all?(&:present?)
  end

  test "handles a genuine concurrent double-submit without raising or duplicating" do
    idempotency_key = SecureRandom.uuid
    from_account = accounts(:depository)
    to_account = accounts(:credit_card)

    # Simulates the race: another request with the same idempotency key wins
    # and commits its transfer in the window between our pre-check (which
    # therefore still sees nothing, hence the first `nil`) and our own
    # Transfer#save! (which then hits the real partial unique index on
    # entries(account_id, idempotency_key) and raises RecordNotUnique,
    # exactly like the DB would under real concurrent requests). The rescue
    # then re-runs the same lookup, this time finding the winner.
    winning_transfer = Transfer::Creator.new(
      family: users(:family_admin).family,
      source_account_id: from_account.id,
      destination_account_id: to_account.id,
      date: Date.current,
      amount: 100,
      idempotency_key: idempotency_key
    ).create
    Transfer::Creator.any_instance.stubs(:find_existing_transfer).returns(nil, winning_transfer)
    Transfer.any_instance.stubs(:save!).raises(ActiveRecord::RecordNotUnique.new("duplicate key value violates unique constraint"))

    assert_no_difference [ "Transfer.count", "Entry.count" ] do
      post transfers_url, params: {
        transfer: {
          from_account_id: from_account.id,
          to_account_id: to_account.id,
          date: Date.current,
          amount: 100,
          name: "Test Transfer",
          idempotency_key: idempotency_key
        }
      }
    end

    assert_redirected_to transactions_path
  end

  test "a RecordNotUnique with no matching transfer is not silently swallowed" do
    idempotency_key = SecureRandom.uuid

    # Defensive-branch coverage: if the unique index ever rejects an insert
    # for a reason other than "another request with this exact idempotency
    # key already won," we must not pretend it succeeded - it should
    # surface as a stale-form error instead of a raw DB exception.
    Transfer::Creator.any_instance.stubs(:find_existing_transfer).returns(nil)
    Transfer.any_instance.stubs(:save!).raises(ActiveRecord::RecordNotUnique.new("duplicate key value violates unique constraint"))

    assert_no_difference [ "Transfer.count", "Entry.count" ] do
      post transfers_url, params: {
        transfer: {
          from_account_id: accounts(:depository).id,
          to_account_id: accounts(:credit_card).id,
          date: Date.current,
          amount: 100,
          name: "Test Transfer",
          idempotency_key: idempotency_key
        }
      }
    end

    assert_response :unprocessable_entity
  end

  test "reusing a key for a genuinely different request does not silently return the old transfer" do
    idempotency_key = SecureRandom.uuid
    from_account = accounts(:depository)
    to_account = accounts(:credit_card)
    other_destination = accounts(:other_liability)

    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: from_account.id,
          to_account_id: to_account.id,
          date: Date.current,
          amount: 100,
          name: "Test Transfer",
          idempotency_key: idempotency_key
        }
      }
    end

    # Simulates a stale hidden field (cached page / reopened dialog) still
    # carrying the first request's key while the user changed the
    # destination account before resubmitting.
    assert_no_difference [ "Transfer.count", "Entry.count" ] do
      post transfers_url, params: {
        transfer: {
          from_account_id: from_account.id,
          to_account_id: other_destination.id,
          date: Date.current,
          amount: 100,
          name: "Test Transfer",
          idempotency_key: idempotency_key
        }
      }
    end

    assert_response :unprocessable_entity
  end

  test "reusing a key with a different fee does not silently return the old transfer" do
    idempotency_key = SecureRandom.uuid
    from_account = accounts(:depository)
    to_account = accounts(:credit_card)

    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: from_account.id,
          to_account_id: to_account.id,
          date: Date.current,
          amount: 100,
          name: "Test Transfer",
          idempotency_key: idempotency_key
        }
      }
    end

    # Same accounts/date/amount/key as the first request, but a fee was
    # added before resubmitting - the persisted effect differs, so this
    # must not be reported as a successful retry of the fee-less transfer.
    assert_no_difference [ "Transfer.count", "Entry.count" ] do
      post transfers_url, params: {
        transfer: {
          from_account_id: from_account.id,
          to_account_id: to_account.id,
          date: Date.current,
          amount: 100,
          name: "Test Transfer",
          source_fee_amount: 5,
          idempotency_key: idempotency_key
        }
      }
    end

    assert_response :unprocessable_entity
  end

  test "reusing a key with a different exchange rate does not silently return the old transfer" do
    idempotency_key = SecureRandom.uuid
    usd_account = accounts(:depository)
    eur_account = users(:family_admin).family.accounts.create!(
      name: "EUR Account",
      balance: 1000,
      currency: "EUR",
      accountable: Depository.new
    )

    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: usd_account.id,
          to_account_id: eur_account.id,
          date: Date.current,
          amount: 100,
          exchange_rate: 0.9,
          idempotency_key: idempotency_key
        }
      }
    end

    # Same accounts/date/amount/key, but a different exchange rate - the
    # persisted inflow amount would differ, so this must not be reported as
    # a successful retry of the first, differently-converted transfer.
    assert_no_difference [ "Transfer.count", "Entry.count" ] do
      post transfers_url, params: {
        transfer: {
          from_account_id: usd_account.id,
          to_account_id: eur_account.id,
          date: Date.current,
          amount: 100,
          exchange_rate: 0.5,
          idempotency_key: idempotency_key
        }
      }
    end

    assert_response :unprocessable_entity
  end

  test "can create transfer with custom exchange rate" do
    usd_account = accounts(:depository)
    eur_account = users(:family_admin).family.accounts.create!(
      name: "EUR Account",
      balance: 1000,
      currency: "EUR",
      accountable: Depository.new
    )

    assert_equal "USD", usd_account.currency
    assert_equal "EUR", eur_account.currency

    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: usd_account.id,
          to_account_id: eur_account.id,
          date: Date.current,
          amount: 100,
          exchange_rate: 0.92
        }
      }
    end

    transfer = Transfer.where(
      "outflow_transaction_id IN (?) AND inflow_transaction_id IN (?)",
      usd_account.transactions.pluck(:id),
      eur_account.transactions.pluck(:id)
    ).last
    assert_not_nil transfer
    assert_equal "USD", transfer.outflow_transaction.entry.currency
    assert_equal "EUR", transfer.inflow_transaction.entry.currency
    assert_equal 100, transfer.outflow_transaction.entry.amount
    assert_in_delta(-92, transfer.inflow_transaction.entry.amount, 0.01)
  end

  test "exchange_rate endpoint returns 400 when from currency is missing" do
    get exchange_rate_url, params: {
      to: "USD"
    }

    assert_response :bad_request
    json_response = JSON.parse(response.body)
    assert_equal "from and to currencies are required", json_response["error"]
  end

  test "exchange_rate endpoint returns 400 when to currency is missing" do
    get exchange_rate_url, params: {
      from: "EUR"
    }

    assert_response :bad_request
    json_response = JSON.parse(response.body)
    assert_equal "from and to currencies are required", json_response["error"]
  end

  test "exchange_rate endpoint returns 400 on invalid date format" do
    get exchange_rate_url, params: {
      from: "EUR",
      to: "USD",
      date: "not-a-date"
    }

    assert_response :bad_request
    json_response = JSON.parse(response.body)
    assert_equal "Invalid date format", json_response["error"]
  end

  test "exchange_rate endpoint returns rate for different currencies" do
    ExchangeRate.expects(:find_or_fetch_rate)
                .with(from: "USD", to: "EUR", date: Date.current)
                .returns(OpenStruct.new(rate: 0.92))

    get exchange_rate_url, params: {
      from: "USD",
      to: "EUR",
      date: Date.current.to_s
    }

    assert_response :success
    json_response = JSON.parse(response.body)
    assert_equal 0.92, json_response["rate"]
  end

  test "exchange_rate endpoint returns error when exchange rate unavailable" do
    ExchangeRate.expects(:find_or_fetch_rate)
                .with(from: "USD", to: "EUR", date: Date.current)
                .returns(nil)

    get exchange_rate_url, params: {
      from: "USD",
      to: "EUR",
      date: Date.current.to_s
    }

    assert_response :not_found
    json_response = JSON.parse(response.body)
    assert_equal "Exchange rate not found", json_response["error"]
  end

  test "cannot create transfer when exchange rate unavailable and no custom rate provided" do
    usd_account = accounts(:depository)
    eur_account = users(:family_admin).family.accounts.create!(
      name: "EUR Account",
      balance: 1000,
      currency: "EUR",
      accountable: Depository.new
    )

    ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)

    assert_no_difference "Transfer.count" do
      post transfers_url, params: {
        transfer: {
          from_account_id: usd_account.id,
          to_account_id: eur_account.id,
          date: Date.current,
          amount: 100
        }
      }
    end

    assert_response :unprocessable_entity
  end

  test "can create transfer with source fee" do
    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: accounts(:depository).id,
          to_account_id: accounts(:credit_card).id,
          date: Date.current,
          amount: 100,
          source_fee_amount: 3
        }
      }
    end

    transfer = Transfer.order(created_at: :desc).first
    assert_equal 100, transfer.amount
    assert_equal 3, transfer.derived_source_fee_amount
    assert_equal 0, transfer.derived_destination_fee_amount
    # Outflow should be principal only (no fee baked in)
    assert_equal 100, transfer.outflow_transaction.entry.amount
    # Inflow should be -(converted_principal)
    assert_equal(-100, transfer.inflow_transaction.entry.amount)
    # Fee transaction should be created
    assert_equal 1, transfer.fee_transactions.count
    fee_tx = transfer.fee_transactions.first
    assert_equal "standard", fee_tx.kind
    assert_equal 3, fee_tx.entry.amount
    assert_equal accounts(:depository).id, fee_tx.entry.account_id
    assert transfer.has_source_fee?
    assert_not transfer.has_destination_fee?
  end

  test "can create transfer with destination fee" do
    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: accounts(:depository).id,
          to_account_id: accounts(:credit_card).id,
          date: Date.current,
          amount: 100,
          destination_fee_amount: 3
        }
      }
    end

    transfer = Transfer.order(created_at: :desc).first
    assert_equal 100, transfer.amount
    assert_equal 0, transfer.derived_source_fee_amount
    assert_equal 3, transfer.derived_destination_fee_amount
    # Outflow should be principal only
    assert_equal 100, transfer.outflow_transaction.entry.amount
    # Inflow should be -(converted_principal)
    assert_equal(-100, transfer.inflow_transaction.entry.amount)
    # Fee transaction should be created
    assert_equal 1, transfer.fee_transactions.count
    fee_tx = transfer.fee_transactions.first
    assert_equal "standard", fee_tx.kind
    assert_equal 3, fee_tx.entry.amount
    assert_equal accounts(:credit_card).id, fee_tx.entry.account_id
    assert_not transfer.has_source_fee?
    assert transfer.has_destination_fee?
  end

  test "can create transfer with both source and destination fees" do
    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: accounts(:depository).id,
          to_account_id: accounts(:credit_card).id,
          date: Date.current,
          amount: 100,
          source_fee_amount: 2,
          destination_fee_amount: 3
        }
      }
    end

    transfer = Transfer.order(created_at: :desc).first
    assert_equal 100, transfer.amount
    assert_equal 2, transfer.derived_source_fee_amount
    assert_equal 3, transfer.derived_destination_fee_amount
    # Outflow should be principal only
    assert_equal 100, transfer.outflow_transaction.entry.amount
    # Inflow should be -(converted_principal)
    assert_equal(-100, transfer.inflow_transaction.entry.amount)
    # Two fee transactions should be created
    assert_equal 2, transfer.fee_transactions.count
    source_fee_tx = transfer.fee_transactions.find { |t| t.entry.account_id == accounts(:depository).id }
    dest_fee_tx = transfer.fee_transactions.find { |t| t.entry.account_id == accounts(:credit_card).id }
    assert_equal 2, source_fee_tx.entry.amount
    assert_equal 3, dest_fee_tx.entry.amount
    assert transfer.has_fees?
  end

  test "derived fee methods reflect fee transaction entry edits" do
    post transfers_url, params: {
      transfer: {
        from_account_id: accounts(:depository).id,
        to_account_id: accounts(:credit_card).id,
        date: Date.current,
        amount: 100,
        source_fee_amount: 3
      }
    }

    transfer = Transfer.order(created_at: :desc).first
    assert_equal 3, transfer.derived_source_fee_amount

    # Simulate an independent edit of the fee transaction entry
    fee_tx = transfer.fee_transactions.first
    fee_tx.entry.update!(amount: 5)

    # Derived fee should reflect the updated entry
    transfer.reload
    assert_equal 5, transfer.derived_source_fee_amount
    assert transfer.has_source_fee?
  end

  test "exchange_rate endpoint returns same_currency for matching currencies" do
    get exchange_rate_url, params: {
      from: "USD",
      to: "USD"
    }

    assert_response :success
    json_response = JSON.parse(response.body)
    assert_equal true, json_response["same_currency"]
    assert_equal 1.0, json_response["rate"]
  end

  test "soft deletes transfer" do
    assert_difference -> { Transfer.count }, -1 do
      delete transfer_url(transfers(:one))
    end
  end

  # The Wise sync links a conversion's legs again on its own, so removing
  # that link rejects it, and the legs stay unlinked.
  test "rejects a link the Wise sync makes, so it stays removed" do
    family = users(:family_admin).family
    wise_item = WiseItem.create!(family: family, name: "Wise", token: "test_token", profile_id: "123", profile_type: :business)
    legs = { "EUR" => -117.5, "GBP" => 100 }.to_h do |currency, amount|
      wise_account = wise_item.wise_accounts.create!(balance_id: "1000000#{currency == 'EUR' ? 1 : 2}", name: "Wise #{currency}",
                                                     currency: currency, raw_payload: { "type" => "STANDARD" })
      account = Account.create!(family: family, name: "Wise #{currency}", balance: 0, currency: currency,
                                accountable: Depository.new(subtype: "checking"))
      AccountProvider.create!(account: account, provider: wise_account)
      side = amount.negative? ? "inflow" : "outflow"
      [ currency, account.entries.create!(external_id: "wise_interbalance_8001_#{side}", source: "wise", amount: amount, currency: currency,
                                          date: Date.current, name: "Conversion", entryable: Transaction.new) ]
    end
    wise_item.link_jar_transfers!
    transfer = Transfer.find_by!(inflow_transaction_id: legs["EUR"].entryable_id)

    delete transfer_url(transfer)

    assert RejectedTransfer.exists?(inflow_transaction_id: legs["EUR"].entryable_id, outflow_transaction_id: legs["GBP"].entryable_id)
    assert_no_difference -> { Transfer.count } do
      wise_item.link_jar_transfers!
    end
    assert_equal %w[standard standard], legs.values.map { |entry| entry.entryable.reload.kind }
  end

  test "can create transfer with tags on both sides" do
    tag = tags(:one)

    assert_difference "Transfer.count", 1 do
      post transfers_url, params: {
        transfer: {
          from_account_id: accounts(:depository).id,
          to_account_id: accounts(:credit_card).id,
          date: Date.current,
          amount: 100,
          tag_ids: [ tag.id ]
        }
      }
    end

    transfer = Transfer.order(:created_at).last
    assert_equal [ tag.id ], transfer.outflow_transaction.tag_ids
    assert_equal [ tag.id ], transfer.inflow_transaction.tag_ids
  end

  test "can update transfer tags on both sides" do
    transfer = transfers(:one)
    tag = tags(:one)

    patch tags_transfer_url(transfer), params: { tag_ids: [ tag.id ] }, as: :json

    assert_response :success
    assert_equal [ tag.id ], transfer.outflow_transaction.reload.tag_ids
    assert_equal [ tag.id ], transfer.inflow_transaction.reload.tag_ids
    assert_equal [ tag.id ], JSON.parse(response.body)["tag_ids"]
  end

  test "update transfer tags ignores tags from other families" do
    transfer = transfers(:one)
    family_tag = tags(:one)
    other_family = Family.create!(name: "Other Family", currency: "USD")
    other_tag = other_family.tags.create!(name: "Foreign")

    patch tags_transfer_url(transfer), params: {
      tag_ids: [ family_tag.id, other_tag.id ]
    }, as: :json

    assert_response :success
    assert_equal [ family_tag.id ], transfer.outflow_transaction.reload.tag_ids
    assert_equal [ family_tag.id ], transfer.inflow_transaction.reload.tag_ids
  end

  test "can clear transfer tags" do
    transfer = transfers(:one)
    tag = tags(:one)
    transfer.outflow_transaction.update!(tag_ids: [ tag.id ])
    transfer.inflow_transaction.update!(tag_ids: [ tag.id ])

    patch tags_transfer_url(transfer), params: { tag_ids: [] }, as: :json

    assert_response :success
    assert_empty transfer.outflow_transaction.reload.tag_ids
    assert_empty transfer.inflow_transaction.reload.tag_ids
  end

  test "update tags requires annotate permission on both transfer sides" do
    # family_member: full_control on depository (outflow), read_only on credit_card (inflow)
    sign_in users(:family_member)
    transfer = transfers(:one)
    tag = tags(:one)
    original_outflow_tags = transfer.outflow_transaction.tag_ids
    original_inflow_tags = transfer.inflow_transaction.tag_ids

    patch tags_transfer_url(transfer), params: { tag_ids: [ tag.id ] }, as: :json

    assert_response :forbidden
    assert_equal I18n.t("accounts.not_authorized"), JSON.parse(response.body)["error"]
    assert_equal original_outflow_tags, transfer.outflow_transaction.reload.tag_ids
    assert_equal original_inflow_tags, transfer.inflow_transaction.reload.tag_ids
  end

  test "confirming requires write permission on both transfer sides" do
    # family_member: full_control on depository (outflow), read_only on credit_card (inflow)
    sign_in users(:family_member)
    transfer = transfers(:one)

    assert_no_changes -> { transfer.inflow_transaction.reload.kind } do
      patch transfer_url(transfer), params: { transfer: { status: "confirmed" } }
    end

    assert_redirected_to transactions_url
    assert transfer.reload.pending?
  end

  test "can add notes to transfer" do
    transfer = transfers(:one)
    assert_nil transfer.notes

    patch transfer_url(transfer), params: { transfer: { notes: "Test notes" } }

    assert_redirected_to transactions_url
    assert_equal "Transfer updated", flash[:notice]
    assert_equal "Test notes", transfer.reload.notes
  end

  test "editing a transfer locks the transfer before its legs" do
    transfer = transfers(:one)
    locking = []
    record = ->(*, payload) do
      sql = payload[:sql]
      locking << sql if sql.include?("FOR UPDATE") || sql.match?(/\A\s*(UPDATE|DELETE)\b/i)
    end

    ActiveSupport::Notifications.subscribed(record, "sql.active_record") do
      patch transfer_url(transfer), params: { transfer: { category_id: categories(:food_and_drink).id, notes: "Rent" } }
    end

    assert_redirected_to transactions_url
    assert_match(/FROM "transfers".*FOR UPDATE/, locking.first)
  end

  test "a category chosen in the transfer editor is locked as the user's" do
    transfer = transfers(:one)
    category = families(:dylan_family).investment_contributions_category

    patch transfer_url(transfer), params: { transfer: { category_id: category.id } }

    outflow = transfer.outflow_transaction.reload
    assert_equal category, outflow.category
    assert outflow.locked?(:category_id), "a cleanup or sync would treat an unlocked choice as its own"
  end

  test "a category re-chosen in the transfer editor stays the user's where the AI had set it" do
    transfer = transfers(:one)
    category = families(:dylan_family).investment_contributions_category
    outflow = transfer.outflow_transaction
    outflow.enrich_attribute(:category_id, category.id, source: "ai")
    outflow.lock_attr!(:category_id)

    patch transfer_url(transfer), params: { transfer: { category_id: category.id } }

    assert_empty Transaction.where(id: outflow.id).without_user_category_lock
    outflow.reload.update!(kind: "funds_movement")
    assert_equal category, outflow.reload.category
  end

  test "a different category chosen in the transfer editor keeps the AI's superseded suggestion" do
    transfer = transfers(:one)
    outflow = transfer.outflow_transaction
    outflow.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
    outflow.lock_attr!(:category_id)
    category = families(:dylan_family).investment_contributions_category

    patch transfer_url(transfer), params: { transfer: { category_id: category.id } }

    assert_equal category, outflow.reload.category
    suggestion = DataEnrichment.find_by(enrichable: outflow, attribute_name: "category_id", source: "ai")
    assert suggestion, "the AI's suggestion was deleted, so the transaction leaves the AI history filter"
    assert_equal true, suggestion.metadata["superseded"]
  end

  test "confirming a transfer keeps the outflow category" do
    transfer = transfers(:one)
    transfer.outflow_transaction.update!(category: categories(:food_and_drink))

    patch transfer_url(transfer), params: { transfer: { status: "confirmed" } }

    assert_redirected_to transactions_url
    assert transfer.reload.confirmed?
    assert_equal categories(:food_and_drink), transfer.outflow_transaction.reload.category
  end

  test "confirming a transfer keeps its notes" do
    transfer = transfers(:one)
    transfer.update!(notes: "Rent split")

    patch transfer_url(transfer), params: { transfer: { status: "confirmed" } }

    assert_redirected_to transactions_url
    assert transfer.reload.confirmed?
    assert_equal "Rent split", transfer.notes
  end

  test "handles rejection without FrozenError" do
    transfer = transfers(:one)

    assert_difference "Transfer.count", -1 do
      patch transfer_url(transfer), params: {
        transfer: {
          status: "rejected"
        }
      }
    end

    assert_redirected_to transactions_url
    assert_equal "Transfer updated", flash[:notice]

    # Verify the transfer was actually destroyed
    assert_raises(ActiveRecord::RecordNotFound) do
      transfer.reload
    end
  end

  test "rejecting a pending match from an account page redraws both rows in place" do
    transfer = transfers(:one)
    assert transfer.pending?, "precondition: the fixture is a pending match"
    inflow_entry = transfer.inflow_transaction.entry
    outflow_entry = transfer.outflow_transaction.entry

    assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do
      patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
        headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }
    end

    assert_response :success
    assert_equal "text/vnd.turbo-stream.html", response.media_type
    assert_select "turbo-stream[action=replace][target=?]", dom_id(inflow_entry)
    assert_select "turbo-stream[action=replace][target=?]", dom_id(outflow_entry)
    assert_select "turbo-stream[action=redirect]", count: 0
    assert_no_match transfer_path(transfer), response.body, "the redrawn rows still offer the rejected match"
  end

  test "rejecting a pending match redraws only the rows the user can see" do
    transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream

    assert_response :success
    assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)
    assert_select "turbo-stream[target=?]", dom_id(transfer.inflow_transaction.entry), count: 0
  end

  test "rejecting a pending match with fees reloads the page, as the fees go with it" do
    transfer = transfers(:one)
    attach_fee(transfer, account: accounts(:depository))

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => transactions_url }

    assert_select "turbo-stream[action=redirect][target=?]", transactions_url
  end

  test "rejecting a pending match with a leg in a split group reloads the page, which draws the group" do
    transfer = transfers(:one)
    outflow_entry = transfer.outflow_transaction.entry
    parent = create_transaction(account: outflow_entry.account, amount: 250, name: "Split parent")
    outflow_entry.update_columns(parent_entry_id: parent.id)

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => transactions_url }

    assert_select "turbo-stream[action=redirect][target=?]", transactions_url
  end

  test "a redrawn leg that still pairs with another transaction offers the transfer hint" do
    transfer = transfers(:one)
    inflow_entry = transfer.inflow_transaction.entry
    create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Another payment")

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,

      headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }

    assert_select "turbo-stream[action=replace][target=?]", dom_id(inflow_entry)
    assert_select "##{dom_id(transfer.inflow_transaction, :transfer_hint)}"
  end

  # A pair touching a transfer is never offered, so destroying the match can
  # free another visible row to pair with one of its legs.
  test "a row the rejection frees to pair with a leg is redrawn with the transfer hint" do
    transfer = transfers(:one)
    inflow_entry = transfer.inflow_transaction.entry
    other = create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Another payment")

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,

      headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }

    assert_select "turbo-stream[action=replace][target=?]", dom_id(other)
    assert_select "##{dom_id(other.transaction, :transfer_hint)}"
  end

  test "a rejection freeing a row inside a split group to pair reloads the page, which draws the group" do
    transfer = transfers(:one)
    inflow_entry = transfer.inflow_transaction.entry
    other = create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Another payment")
    parent = create_transaction(account: accounts(:depository), amount: 500, name: "Split parent")
    other.update_columns(parent_entry_id: parent.id)

    account_page = account_url(transfer.outflow_transaction.entry.account)
    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => account_page }

    assert_select "turbo-stream[action=redirect][target=?]", account_page
  end

  test "a rejection freeing more rows than the bound to pair reloads the page" do
    transfer = transfers(:one)
    inflow_entry = transfer.inflow_transaction.entry
    (TransfersController::MAX_REDRAWN_PAIRED_ROWS + 1).times do |i|
      create_transaction(account: accounts(:depository), amount: -inflow_entry.amount, date: inflow_entry.date, name: "Candidate #{i}")
    end

    account_page = account_url(transfer.outflow_transaction.entry.account)
    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => account_page }

    assert_select "turbo-stream[action=redirect][target=?]", account_page
  end

  test "a rejection leaving no row the user can see reloads the page" do
    transfer = transfers(:one)
    TransfersController.any_instance.stubs(:accessible_transaction_entries).returns([])

    account_page = account_url(transfer.outflow_transaction.entry.account)
    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => account_page }

    assert_select "turbo-stream[action=redirect][target=?]", account_page
  end

  # The transactions list draws a transfer once, by its outflow, so the
  # inflow has no row there to redraw.
  test "rejecting a pending match whose legs are both on the transactions list reloads the page" do
    transfer = transfers(:one)

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => transactions_url }

    assert_select "turbo-stream[action=redirect][target=?]", transactions_url
    assert_not Transfer.exists?(transfer.id)
  end

  test "rows redrawn on an account page keep the account view's signed amounts" do
    transfer = transfers(:one)
    transfer.outflow_transaction.update_columns(kind: "funds_movement")

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,

      headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }

    assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)
    assert_no_match "+/-", response.body
  end

  test "an account page's reject button carries no view of its own" do
    transfer = transfers(:one)

    get account_url(transfer.outflow_transaction.entry.account)

    assert_select "##{dom_id(transfer.outflow_transaction, :transfer_match)} form[action=?]",
      transfer_path(transfer, transfer: { status: "rejected" })
  end

  # The page a request comes from decides the view, so a client flag cannot
  # claim the account view on the transactions list.
  test "a view_ctx param does not make the transactions list redraw a rejection in place" do
    transfer = transfers(:one)

    patch transfer_url(transfer, view_ctx: "account"), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => transactions_url }

    assert_select "turbo-stream[action=redirect][target=?]", transactions_url
  end

  test "editing a pending transfer on an account page redraws its rows in the account view" do
    transfer = transfers(:one)
    transfer.outflow_transaction.update_columns(kind: "funds_movement")

    patch transfer_url(transfer), params: { transfer: { notes: "Rent" } }, as: :turbo_stream,
      headers: { "Referer" => account_url(transfer.outflow_transaction.entry.account) }

    assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)
    assert_no_match "+/-", response.body
  end

  test "editing a pending transfer on the transactions list redraws its rows in the list's view" do
    transfer = transfers(:one)
    transfer.outflow_transaction.update_columns(kind: "funds_movement")

    patch transfer_url(transfer), params: { transfer: { notes: "Rent" } }, as: :turbo_stream,
      headers: { "Referer" => transactions_url }

    assert_select "turbo-stream[action=replace][target=?]", dom_id(transfer.outflow_transaction.entry)
    assert_match "+/-", response.body
  end

  test "rejecting a confirmed transfer reloads the page, whose totals it moves" do
    transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan, status: "confirmed")

    patch transfer_url(transfer), params: { transfer: { status: "rejected" } }, as: :turbo_stream,
      headers: { "Referer" => transactions_url }

    assert_select "turbo-stream[action=redirect][target=?]", transactions_url
  end

  test "can reject a match when only the outflow account is accessible" do
    # Confirmed, so the legs carry transfer kinds that rejecting must reset
    transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan, status: "confirmed")

    assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do
      patch transfer_url(transfer), params: { transfer: { status: "rejected" } }
    end

    assert_redirected_to transactions_url
    assert_equal "standard", transfer.outflow_transaction.reload.kind
    assert_equal "standard", transfer.inflow_transaction.reload.kind
  end

  test "can reject a match when only the inflow account is accessible" do
    transfer = cross_owner_transfer(outflow_account: member_loan, inflow_account: accounts(:depository))

    assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do
      patch transfer_url(transfer), params: { transfer: { status: "rejected" } }
    end

    assert_redirected_to transactions_url
  end

  test "can unlink a match when only one side is accessible" do
    transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)

    assert_difference -> { Transfer.count }, -1 do
      delete transfer_url(transfer)
    end
  end

  test "cannot unlink a match from one side when a fee sits in the other account" do
    transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)
    writable_fee = attach_fee(transfer, account: accounts(:depository))
    unwritable_fee = attach_fee(transfer, account: member_loan)

    assert_no_difference -> { Transfer.count } do
      patch transfer_url(transfer), params: { transfer: { status: "rejected" } }
      delete transfer_url(transfer)
    end

    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
    assert Transfer.exists?(transfer.id)
    assert Transaction.exists?(writable_fee.id)
    assert Transaction.exists?(unwritable_fee.id)
  end

  test "can reject a match from one side when its fees sit in a writable account" do
    transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)
    fee = attach_fee(transfer, account: accounts(:depository))

    assert_difference -> { Transfer.count } => -1, -> { RejectedTransfer.count } => 1 do
      patch transfer_url(transfer), params: { transfer: { status: "rejected" } }
    end

    assert_not Transaction.exists?(fee.id)
  end

  test "cannot edit a match when only the inflow account is accessible" do
    transfer = cross_owner_transfer(outflow_account: member_loan, inflow_account: accounts(:depository))

    patch transfer_url(transfer), params: { transfer: { status: "confirmed", notes: "Nope" } }

    assert_response :not_found
    assert transfer.reload.pending?
    assert_nil transfer.notes
  end

  test "cannot edit a match when only the outflow account is accessible" do
    transfer = cross_owner_transfer(outflow_account: accounts(:depository), inflow_account: member_loan)
    inflow_amount = transfer.inflow_transaction.entry.amount

    patch transfer_url(transfer), params: { transfer: { status: "confirmed", amount: transfer.amount + 10, notes: "Nope" } }

    assert_response :not_found
    assert transfer.reload.pending?
    assert_nil transfer.notes
    assert_equal inflow_amount, transfer.inflow_transaction.entry.reload.amount
  end

  test "cannot reject a match when neither side is accessible" do
    vehicle = accounts(:vehicle)
    vehicle.update!(owner: users(:family_member))
    transfer = cross_owner_transfer(outflow_account: vehicle, inflow_account: member_loan)

    assert_no_difference -> { Transfer.count } do
      patch transfer_url(transfer), params: { transfer: { status: "rejected" } }
    end

    assert_response :not_found
  end

  test "show names each side's transaction beside its amount" do
    transfer = transfers(:one)
    transfer.outflow_transaction.entry.update!(name: "Card bill sent from checking")
    transfer.inflow_transaction.entry.update!(name: "Payment received, thank you")

    get transfer_url(transfer)

    assert_response :success
    assert_select "dt", text: I18n.t("transfers.show.transaction"), count: 2
    assert_select "dd", text: "Card bill sent from checking"
    assert_select "dd", text: "Payment received, thank you"
  end

  test "show leaves out the name of a side whose account the user cannot see" do
    transfer = cross_owner_transfer(outflow_account: member_loan, inflow_account: accounts(:depository))
    transfer.outflow_transaction.entry.update!(name: "Private loan payment")
    transfer.inflow_transaction.entry.update!(name: "Money in")

    get transfer_url(transfer)

    assert_response :success
    assert_select "dt", text: I18n.t("transfers.show.transaction"), count: 1
    assert_select "dd", text: "Money in"
    assert_select "dd", text: "Private loan payment", count: 0
    assert_no_match "Private loan payment", response.body
  end

  test "show offers the investment contribution switch only for transfers into an investment account" do
    contribution = create_confirmed_transfer(to: accounts(:investment))
    payment = create_confirmed_transfer(to: accounts(:credit_card))

    get transfer_url(contribution)
    assert_select "input[type=checkbox][name='transfer[investment_contribution]'][checked]"

    get transfer_url(payment)
    assert_select "input[name='transfer[investment_contribution]']", count: 0
  end

  test "turning off the investment contribution makes a plain transfer and reloads the page" do
    transfer = create_confirmed_transfer(to: accounts(:investment))

    patch transfer_url(transfer),
          params: { transfer: { investment_contribution: "0" } },
          headers: { "Accept" => "text/vnd.turbo-stream.html", "Referer" => transactions_url }

    assert_response :success
    assert_includes response.body, %(action="redirect")
    assert_equal "funds_movement", transfer.outflow_transaction.reload.kind
  end

  test "turning the investment contribution back on restores it" do
    transfer = create_confirmed_transfer(to: accounts(:investment))
    transfer.update_investment_contribution!(false)

    patch transfer_url(transfer), params: { transfer: { investment_contribution: "1" } }

    assert_redirected_to transactions_url
    assert_equal "investment_contribution", transfer.outflow_transaction.reload.kind
  end

  test "switching the investment contribution requires write permission on both transfer sides" do
    sign_in users(:family_member)
    accounts(:investment).account_shares.create!(user: users(:family_member), permission: "read_only")
    transfer = create_confirmed_transfer(to: accounts(:investment))

    patch transfer_url(transfer), params: { transfer: { investment_contribution: "0" } }

    assert_redirected_to transactions_url
    assert_equal "investment_contribution", transfer.outflow_transaction.reload.kind
  end

  test "mark_as_recurring creates a recurring transfer" do
    transfer = transfers(:one)
    family = users(:family_admin).family
    family.recurring_transactions.destroy_all

    assert_difference -> { RecurringTransaction.where(family: family).count }, +1 do
      post mark_as_recurring_transfer_url(transfer)
    end

    rt = RecurringTransaction.where(family: family).last
    assert rt.transfer?
    assert_equal transfer.outflow_transaction.entry.account, rt.account
    assert_equal transfer.inflow_transaction.entry.account, rt.destination_account
    assert rt.manual?
    assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]
    assert_redirected_to transactions_path
  end

  test "mark_as_recurring is idempotent: second call flashes already-exists" do
    transfer = transfers(:one)
    family = users(:family_admin).family
    family.recurring_transactions.destroy_all

    post mark_as_recurring_transfer_url(transfer)
    assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]

    assert_no_difference -> { RecurringTransaction.where(family: family).count } do
      post mark_as_recurring_transfer_url(transfer)
    end
    assert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]
  end

  test "mark_as_recurring accepts two transfers with the same accounts and amount on different days" do
    family = users(:family_admin).family
    family.recurring_transactions.destroy_all
    first = create_dated_transfer(date: Date.new(2026, 1, 1))
    second = create_dated_transfer(date: Date.new(2026, 1, 28))

    assert_difference -> { RecurringTransaction.where(family: family).count }, +2 do
      post mark_as_recurring_transfer_url(first)
      assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]
      post mark_as_recurring_transfer_url(second)
      assert_equal I18n.t("recurring_transactions.transfer_marked_as_recurring"), flash[:notice]
    end

    assert_equal [ 1, 28 ], RecurringTransaction.where(family: family).order(:expected_day_of_month).pluck(:expected_day_of_month)
  end

  test "mark_as_recurring recognises a transfer posted a weekend later than its series" do
    family = users(:family_admin).family
    family.recurring_transactions.destroy_all
    july = create_dated_transfer(date: Date.new(2026, 7, 1))
    # August 1 is a Saturday: the standing order posts on Monday the 3rd.
    august = create_dated_transfer(date: Date.new(2026, 8, 3))

    post mark_as_recurring_transfer_url(july)

    assert_no_difference -> { RecurringTransaction.where(family: family).count } do
      post mark_as_recurring_transfer_url(august)
    end
    assert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]
  end

  test "mark_as_recurring flags a second transfer on the same day of the same series as already existing" do
    family = users(:family_admin).family
    family.recurring_transactions.destroy_all
    january = create_dated_transfer(date: Date.new(2026, 1, 28))
    february = create_dated_transfer(date: Date.new(2026, 2, 28))

    post mark_as_recurring_transfer_url(january)

    assert_no_difference -> { RecurringTransaction.where(family: family).count } do
      post mark_as_recurring_transfer_url(february)
    end
    assert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]
  end

  test "mark_as_recurring reports already-exists when a concurrent request wins the insert" do
    family = users(:family_admin).family
    family.recurring_transactions.destroy_all
    transfer = create_dated_transfer(date: Date.new(2026, 1, 28))
    winner = RecurringTransaction.create_from_transfer(transfer)

    # Our lookup misses, the other request's insert has already landed when
    # ours collides with it.
    RecurringTransaction.stubs(:transfer_series_for).returns(nil).then.returns(winner)
    RecurringTransaction.stubs(:create_from_transfer).raises(ActiveRecord::RecordNotUnique)

    assert_no_difference -> { RecurringTransaction.where(family: family).count } do
      post mark_as_recurring_transfer_url(transfer)
    end
    assert_equal I18n.t("recurring_transactions.transfer_already_exists"), flash[:alert]
  end

  test "mark_as_recurring is rejected when recurring_transactions_disabled" do
    transfer = transfers(:one)
    family = users(:family_admin).family
    family.update!(recurring_transactions_disabled: true)
    family.recurring_transactions.destroy_all

    assert_no_difference -> { RecurringTransaction.where(family: family).count } do
      post mark_as_recurring_transfer_url(transfer)
    end
    assert_equal I18n.t("recurring_transactions.transfer_feature_disabled"), flash[:alert]
  end

  test "update leaves the amount of a transfer whose leg is a split part" do
    parent = create_transaction(account: accounts(:depository), amount: 100, name: "Mortgage")
    part = parent.split!([ { name: "Principal", amount: 60 }, { name: "Interest", amount: 40 } ]).first
    transfer = link_split_part_to_loan(part)

    patch transfer_url(transfer), params: { transfer: { amount: "75", notes: "Principal" } }

    assert_equal 60, part.reload.amount
    assert_equal(-60, transfer.inflow_transaction.entry.reload.amount)
    assert_equal "Principal", transfer.reload.notes
  end

  private
    def create_dated_transfer(date:, amount: 2000)
      outflow_entry = create_transaction(date: date, account: accounts(:depository), amount: amount)
      inflow_entry = create_transaction(date: date, account: accounts(:investment), amount: -amount)

      Transfer.create!(inflow_transaction: inflow_entry.transaction, outflow_transaction: outflow_entry.transaction).tap(&:confirm!)
    end

    def create_confirmed_transfer(to:)
      outflow_entry = create_transaction(date: Date.current, account: accounts(:depository), amount: 500)
      inflow_entry = create_transaction(date: Date.current, account: to, amount: -500)

      Transfer.create!(inflow_transaction: inflow_entry.transaction, outflow_transaction: outflow_entry.transaction).tap(&:confirm!)
    end

    # A loan owned by family_member and not shared with family_admin
    def member_loan
      accounts(:loan).tap { |loan| loan.update!(owner: users(:family_member)) }
    end

    def cross_owner_transfer(outflow_account:, inflow_account:, status: "pending")
      outflow = create_transaction(account: outflow_account, amount: 250, kind: "funds_movement")
      inflow = create_transaction(account: inflow_account, amount: -250, kind: "funds_movement")

      Transfer.create!(outflow_transaction: outflow.transaction, inflow_transaction: inflow.transaction, status: status)
    end

    def attach_fee(transfer, account:)
      create_transaction(account: account, amount: 5, name: "Transfer fee").transaction.tap do |fee|
        fee.update!(transfer: transfer)
      end
    end
end