Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
74.3 KB
Raw Blame
require "test_helper"

class LoansControllerTest < ActionDispatch::IntegrationTest
  include AccountableResourceInterfaceTest

  setup do
    sign_in @user = users(:family_admin)
    @account = accounts(:loan)
  end

  test "old forms without a schedule snapshot cannot overwrite provider rows or account fields" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),
                          variable_rate_schedule: { "2026-01-01" => "6" })
    @account.loan.enrich_attributes(
      { variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" } }, source: "redbark"
    )
    original_name = @account.name
    original_balance = @account.balance
    [ nil, "" ].each do |snapshot|
      attrs = { rate_changes: [ { effective_date: "2026-01-01", rate: "6" } ] }
      attrs[:rate_schedule_snapshot] = snapshot unless snapshot.nil?

      assert_no_difference [ "Entry.count", "DataEnrichment.count" ] do
        patch loan_path(@account), params: { account: {
          name: "Outdated edit", balance: original_balance - 1000, accountable_attributes: attrs
        } }
      end

      assert_response :unprocessable_entity
      assert_match I18n.t("loans.edit.stale_rate_schedule"), response.body
      assert_select "input[name='account[accountable_attributes][rate_changes][][effective_date]'][value='2026-02-01']", count: 1
      assert_equal original_name, @account.reload.name
      assert_equal original_balance, @account.balance
      assert_equal({ "2026-01-01" => "6", "2026-02-01" => "7" }, @account.loan.variable_rate_schedule)
    end
  end

  test "an old form cannot clear the schedule without a snapshot" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),
                          variable_rate_schedule: { "2026-01-01" => "6" })

    patch loan_path(@account), params: { account: { accountable_attributes: { rate_changes: [ "" ] } } }

    assert_response :unprocessable_entity
    assert_equal({ "2026-01-01" => "6" }, @account.loan.reload.variable_rate_schedule)
  end

  test "a stale form preserves provider dates while deleting and adding its own rows" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),
                          variable_rate_schedule: { "2026-01-01" => "6" })
    get edit_loan_path(@account)
    assert_response :success
    snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]

    @account.loan.enrich_attributes(
      { variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" } }, source: "redbark"
    )
    patch loan_path(@account), params: { account: { accountable_attributes: {
      rate_schedule_snapshot: snapshot,
      rate_changes: [ { effective_date: "2026-03-01", rate: "8" } ]
    } } }

    assert_response :redirect
    assert_equal({ "2026-02-01" => "7", "2026-03-01" => "8.0" }, @account.loan.reload.variable_rate_schedule)
  end

  {
    "deleting" => [ [ "" ], { "2026-01-01" => "7" } ],
    "moving" => [ [ "", { effective_date: "2026-01-15", rate: "6" } ], { "2026-01-01" => "7", "2026-01-15" => "6.0" } ]
  }.each do |action, (rate_changes, expected)|
    test "a stale form #{action} a rendered row keeps the provider's correction of it" do
      @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),
                            variable_rate_schedule: { "2026-01-01" => "6" })
      get edit_loan_path(@account)
      assert_response :success
      snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]

      @account.loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")
      patch loan_path(@account), params: { account: { accountable_attributes: {
        rate_schedule_snapshot: snapshot, rate_changes: rate_changes
      } } }

      assert_response :redirect
      assert_equal expected, @account.loan.reload.variable_rate_schedule
    end
  end

  test "an invalid schedule snapshot is rejected even with no changed rate rows" do
    @account.loan.update!(rate_type: "variable", variable_rate_schedule: {})
    patch loan_path(@account), params: { account: { accountable_attributes: {
      rate_schedule_snapshot: "[]", rate_changes: []
    } } }

    assert_response :unprocessable_entity
    assert_match I18n.t("activerecord.errors.models.loan.invalid_rate_schedule_snapshot"), response.body
    assert_empty @account.loan.reload.variable_rate_schedule
  end

  test "malformed snapshots redisplay persisted provider rows and cannot delete them on retry" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),
                          variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" })
    [ "{broken", "[]", "null", "5" ].each do |invalid_snapshot|
      patch loan_path(@account), params: { account: { accountable_attributes: {
        rate_schedule_snapshot: invalid_snapshot, rate_changes: [ { effective_date: "2026-01-01", rate: "6" } ]
      } } }

      assert_response :unprocessable_entity
      assert_match I18n.t("activerecord.errors.models.loan.invalid_rate_schedule_snapshot"), response.body
      assert_no_match I18n.t("activerecord.errors.models.loan.invalid_rate_change"), response.body
      assert_select "input[name='account[accountable_attributes][rate_changes][][effective_date]'][value='2026-02-01']", count: 1
      snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]
      rows = css_select("[data-rate-change-row]").filter_map do |row|
        date = row.at_css("input[name$='[effective_date]']")["value"]
        rate = row.at_css("input[name$='[rate]']")["value"]
        { effective_date: date, rate: rate } if date.present?
      end

      patch loan_path(@account), params: { account: { accountable_attributes: {
        rate_schedule_snapshot: snapshot, rate_changes: rows
      } } }
      assert_response :redirect
      assert_equal({ "2026-01-01" => "6", "2026-02-01" => "7" }, @account.loan.reload.variable_rate_schedule)
    end
  end

  test "an unchanged form row does not overwrite a provider correction on the same date" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),
                          variable_rate_schedule: { "2026-01-01" => "0.6e1" })
    snapshot = @account.loan.rate_schedule_snapshot
    @account.loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")

    patch loan_path(@account), params: { account: { name: "Reviewed", accountable_attributes: {
      rate_schedule_snapshot: snapshot, rate_changes: [ { effective_date: "2026-01-01", rate: "6.0" } ]
    } } }

    assert_response :redirect
    assert_equal({ "2026-01-01" => "7" }, @account.loan.reload.variable_rate_schedule)
  end

  test "rows shown after a validation error can be removed on resubmission" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1), variable_rate_schedule: {})
    snapshot = @account.loan.rate_schedule_snapshot
    @account.loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")

    patch loan_path(@account), params: { account: { accountable_attributes: {
      rate_schedule_snapshot: snapshot, rate_changes: [ { effective_date: "", rate: "8" } ]
    } } }
    assert_response :unprocessable_entity
    snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]
    assert_equal({ "2026-01-01" => "7" }, JSON.parse(snapshot))

    patch loan_path(@account), params: { account: { accountable_attributes: {
      rate_schedule_snapshot: snapshot, rate_changes: []
    } } }
    assert_response :redirect
    assert_empty @account.loan.reload.variable_rate_schedule
  end

  test "a failed balance update preserves provider rows through the rendered form and retry" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),
                          variable_rate_schedule: { "2026-01-01" => "6" })
    snapshot = @account.loan.rate_schedule_snapshot
    @account.loan.enrich_attributes(
      { variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" } }, source: "redbark"
    )
    failure = Account::CurrentBalanceManager::Result.new(success?: false, changes_made?: false, error: "Balance update failed")
    Account.any_instance.stubs(:set_current_balance).returns(failure)

    patch loan_path(@account), params: { account: { balance: @account.balance - 1000, accountable_attributes: {
      rate_schedule_snapshot: snapshot,
      rate_changes: [ { effective_date: "2026-03-01", rate: "8" }, { effective_date: "", rate: "9" } ]
    } } }
    assert_response :unprocessable_entity
    assert_select "input[name='account[accountable_attributes][rate_changes][][effective_date]'][value='2026-02-01']", count: 1
    assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", count: 1
    snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]
    rows = css_select("[data-rate-change-row]").filter_map do |row|
      date = row.at_css("input[name$='[effective_date]']")["value"]
      rate = row.at_css("input[name$='[rate]']")["value"]
      { effective_date: date, rate: rate } if date.present?
    end
    Account.any_instance.unstub(:set_current_balance)

    patch loan_path(@account), params: { account: { balance: @account.balance - 1000, accountable_attributes: {
      rate_schedule_snapshot: snapshot, rate_changes: rows
    } } }
    assert_response :redirect
    assert_equal({ "2026-02-01" => "7", "2026-03-01" => "8.0" }, @account.loan.reload.variable_rate_schedule)
  end

  # The overview only shows what the loan actually records: a leverage figure
  # needs a down payment, and an insurance card needs a premium. A loan with
  # neither must not grow cards reading zero, which would say the borrower has
  # insurance costing nothing rather than none.
  test "the overview shows leverage and insurance once they are recorded" do
    get account_path(@account)
    assert_response :success
    assert_no_match(/Leverage/, response.body, "nothing to compute a ratio from yet")
    # The summary card's own title, not the word: the repayment breakdown below
    # the cards has an "Insurance" row of its own, which would satisfy a match
    # on the page body with the card deleted.
    assert_select "h4", text: "Insurance", count: 0, message: "and no premium recorded"

    @account.loan.update!(
      down_payment: 100_000, interest_rate: 5, term_months: 120, rate_type: "fixed",
      start_date: 2.years.ago.to_date, insurance_rate: 0.36, insurance_rate_type: "level_term"
    )

    get account_path(@account)
    assert_response :success

    assert_match(/Leverage/, response.body)
    assert_match(/5\.0x/, response.body, "500,000 borrowed against 100,000 put in")
    assert_match(/Moderate/, response.body, "and the band that ratio sits in")
    assert_select "h4", text: "Insurance", count: 1, message: "the insurance summary card"
    assert_match(/Total Cost/, response.body)
    assert_select "[data-controller='donut-chart']", count: 1, message: "the repayment ring"
    # The amount borrowed is money like the ratio beside it, so Privacy Mode
    # must blur it too.
    assert_select "[data-controller='donut-chart'] p.privacy-sensitive", text: /of \$500,000/, count: 1
  end

  # The Schedule tab's "Total Cost" is what the borrower repays: principal plus
  # interest. Both tabs render in one request, so the Overview's card must
  # either show that same figure or say what it adds -- a premium folded in
  # under the same title put two different "Total Cost" amounts on one page.
  test "the overview's total cost agrees with the schedule's and names the premium it adds" do
    loan = @account.loan
    loan.update!(interest_rate: 5, term_months: 120, rate_type: "fixed", start_date: 2.years.ago.to_date)

    get account_path(@account)
    uninsured = card_values("Total Cost")
    assert_equal 2, uninsured.size, "precondition: the Overview and Schedule tabs each render the card"
    assert_equal 1, uninsured.uniq.size, "with no premium the two figures are the same figure"

    loan.update!(insurance_rate: 0.36, insurance_rate_type: "level_term")
    loan = Loan.find(loan.id)

    get account_path(@account)
    assert_equal uninsured.first(1), card_values("Total Cost"),
                 "one card still calls itself Total Cost, and it has not moved"
    assert_equal [ format_money(loan.amortization_schedule.total_paid + loan.total_insurance) ],
                 card_values("Total Cost incl. Insurance"),
                 "the Overview names the premium it adds, and adds it to the Schedule's figure"
  end

  # A rate saved on a loan with no term has no schedule to project a premium
  # against. The card must still say a policy is recorded rather than vanish,
  # which read as though the save had been lost.
  test "a recorded insurance rate shows even when no premium can be projected" do
    @account.loan.update!(term_months: nil, insurance_rate: 0.36, insurance_rate_type: "level_term")
    assert_nil Loan.find(@account.loan.id).insurance, "precondition: nothing to project against"

    get account_path(@account)
    assert_response :success
    assert_equal [ "0.36% a year" ], card_values("Insurance")
  end

  # A negative opening valuation (imports produce them) has no leverage band,
  # and the card built its label from the band -- a key that does not exist.
  test "a negative opening balance shows no leverage card rather than a missing translation" do
    @account.loan.update!(down_payment: 100_000)
    @account.entries.create!(
      date: Date.current - 2.years, name: "Opening balance", amount: -500_000, currency: @account.currency,
      entryable: Valuation.new(kind: "opening_anchor")
    )
    assert @account.loan.original_balance.negative?, "precondition: the opening balance is negative"

    get account_path(@account)
    assert_response :success
    assert_no_match(/translation missing: en\.loans/, response.body)
    assert_select "h4", text: "Leverage", count: 0
  end

  # The form renders these fields, so a save must keep them. Measured against
  # the loan's own state before the request: all three start blank.
  test "updates the down payment and insurance terms from the form" do
    loan = @account.loan
    assert_nil loan.down_payment
    assert_nil loan.insurance_rate
    assert_nil loan.insurance_rate_type

    patch loan_path(@account), params: {
      account: {
        accountable_type: "Loan",
        accountable_attributes: {
          id: @account.accountable_id,
          down_payment: "100000", insurance_rate: "0.36", insurance_rate_type: "level_term"
        }
      }
    }

    assert_redirected_to @account
    loan.reload
    assert_equal BigDecimal("100000"), loan.down_payment
    assert_equal BigDecimal("0.36"), loan.insurance_rate
    assert_equal "level_term", loan.insurance_rate_type
  end

  # The select passes `label: true`, so its text comes from the Loan model's
  # attribute name. Without a translation Rails humanizes it to "Subtype" in
  # every locale.
  test "the loan type select is labelled from the locale" do
    get new_loan_url
    assert_response :success
    assert_select "label[for=account_accountable_attributes_subtype]", text: "Loan type"
  end

  # The type select's blank option is the form's "None": no type recorded, read
  # as decreasing. It submits an empty string, which must clear the type rather
  # than fail validation (and the column's check constraint, which admits NULL
  # but not '').
  test "the insurance type's blank option clears a recorded type" do
    @account.loan.update!(insurance_rate: 0.36, insurance_rate_type: "level_term")

    patch loan_path(@account), params: {
      account: {
        accountable_type: "Loan",
        accountable_attributes: { id: @account.accountable_id, insurance_rate_type: "" }
      }
    }

    assert_redirected_to @account
    assert_nil @account.loan.reload.insurance_rate_type
  end

  test "creates with loan details" do
    assert_difference -> { Account.count } => 1,
      -> { Loan.count } => 1,
      -> { Valuation.count } => 1,
      -> { Entry.count } => 1 do
      post loans_path, params: {
        account: {
          name: "New Loan",
          balance: 50000,
          currency: "USD",
          institution_name: "Local Bank",
          institution_domain: "localbank.example",
          notes: "Mortgage notes",
          accountable_type: "Loan",
          accountable_attributes: {
            subtype: "mortgage",
            interest_rate: 5.5,
            term_months: 60,
            rate_type: "fixed",
            initial_balance: 50000
          }
        }
      }
    end

    created_account = Account.order(:created_at).last

    assert_equal "New Loan", created_account.name
    assert_equal 50000, created_account.balance
    assert_equal "USD", created_account.currency
    assert_equal "Local Bank", created_account[:institution_name]
    assert_equal "localbank.example", created_account[:institution_domain]
    assert_equal "Mortgage notes", created_account[:notes]
    assert_equal "mortgage", created_account.accountable.subtype
    assert_equal 5.5, created_account.accountable.interest_rate
    assert_equal 60, created_account.accountable.term_months
    assert_equal "fixed", created_account.accountable.rate_type
    assert_equal 50000, created_account.accountable.initial_balance

    assert_redirected_to created_account
    assert_equal "Loan account created", flash[:notice]
    assert_enqueued_with(job: SyncJob)
  end

  # The form offers a day-count convention, and a select is worth nothing if the
  # controller drops the value. This is the end-to-end path the model and engine
  # tests do not cover: without `:day_count_convention` in
  # `permitted_accountable_attributes` the parameter is filtered out, the loan
  # keeps its old convention, and every future schedule ignores the choice.
  test "the day-count convention chosen on create is saved" do
    post loans_path, params: {
      account: {
        name: "Tracker",
        balance: 50000,
        currency: "USD",
        accountable_type: "Loan",
        accountable_attributes: {
          subtype: "mortgage",
          interest_rate: 5.5,
          term_months: 60,
          rate_type: "fixed",
          initial_balance: 50000,
          day_count_convention: "actual_actual"
        }
      }
    }

    assert_equal "actual_actual", Loan.order(:created_at).last.day_count_convention,
                 "the controller filtered the convention out of create"
  end

  test "the day-count convention chosen on the form is saved" do
    assert_equal "thirty_360", @account.loan.day_count_convention

    patch loan_path(@account), params: {
      account: {
        accountable_attributes: {
          id: @account.accountable_id,
          day_count_convention: "actual_365"
        }
      }
    }

    assert_equal "actual_365", @account.loan.reload.day_count_convention,
                 "the controller filtered out the convention the user chose"
  end

  test "saving principal_only_transfers queues a balance sync" do
    patch loan_path(@account), params: {
      account: {
        accountable_attributes: {
          id: @account.accountable_id,
          principal_only_transfers: "1"
        }
      }
    }

    assert @account.loan.reload.principal_only_transfers?
    assert_enqueued_jobs 1, only: SyncJob
  end

  test "saving an unrelated loan field does not queue a balance sync" do
    assert_no_enqueued_jobs(only: SyncJob) do
      patch loan_path(@account), params: { account: { name: "Renamed Loan" } }
    end
  end

  # #3383: the opening anchor holds the original principal, so
  # it belongs on the day the loan was drawn down, not on the form's separate
  # opening balance date (which defaults to today minus two years).
  test "a new loan's opening anchor is dated on its start date" do
    account = create_loan(start_date: Date.new(2020, 1, 15))

    anchor = account.valuations.opening_anchor.first.entry
    assert_equal Date.new(2020, 1, 15), anchor.date
    assert_equal 400_000, anchor.amount
  end

  test "a new loan's recorded balance opens on its principal at its start date" do
    start_date = Date.new(2020, 1, 15)
    account = create_loan(start_date: start_date)
    Balance::Materializer.new(account, strategy: :forward).materialize_balances

    series = account.balance_series(
      period: Period.custom(start_date: start_date, end_date: Date.current),
      interval: "1 month"
    )
    assert_equal 400_000, series.values.first.value.amount
    assert_equal start_date, account.balances.minimum(:date)
  end

  test "a new loan keeps its entered current balance" do
    account = create_loan(start_date: Date.new(2020, 1, 15))
    Balance::Materializer.new(account, strategy: :forward).materialize_balances

    today = account.entries.valuations.find_by(date: Date.current)
    assert_not_nil today
    assert_equal 399_600, today.amount
    assert_equal 399_600, account.balances.find_by(date: Date.current).balance
  end

  test "a loan without a start date keeps the form's opening date" do
    opening_balance_date = Date.current - 3.years # not the manager's own two-year default
    account = create_loan(start_date: nil, opening_balance_date: opening_balance_date)

    assert_equal opening_balance_date, account.valuations.opening_anchor.first.entry.date
  end

  test "a loan with a start date but no original balance keeps the form's opening date" do
    # Without a principal the anchor holds the entered current balance, which
    # was not the balance on the start date.
    opening_balance_date = Date.current - 3.years
    account = create_loan(start_date: Date.new(2020, 1, 15), initial_balance: nil,
                          opening_balance_date: opening_balance_date)

    anchor = account.valuations.opening_anchor.first.entry
    assert_equal opening_balance_date, anchor.date
    assert_equal 399_600, anchor.amount
  end

  # An anchor on or before Entry.min_supported_date would fail Entry's own
  # validation and the form would re-render; the loan is created instead.
  test "a loan started on the earliest supported entry date is created with the form's opening date" do
    opening_balance_date = Date.current - 3.years
    assert_difference "Account.count", 1 do
      account = create_loan(start_date: Entry.min_supported_date, opening_balance_date: opening_balance_date)
      assert_equal opening_balance_date, account.valuations.opening_anchor.first.entry.date
    end
  end

  test "a loan started today has its opening anchor today and no reconciliation" do
    account = create_loan(start_date: Date.current)

    valuations = account.entries.valuations
    assert_equal 1, valuations.count
    assert_equal Date.current, valuations.first.date
    assert_equal 400_000, valuations.first.amount
    assert_equal "opening_anchor", valuations.first.entryable.kind
  end

  test "updates with loan details" do
    assert_no_difference [ "Account.count", "Loan.count" ] do
      patch loan_path(@account), params: {
        account: {
          name: "Updated Loan",
          balance: 45000,
          currency: "USD",
          institution_name: "Updated Bank",
          institution_domain: "updatedbank.example",
          notes: "Updated loan notes",
          accountable_type: "Loan",
          accountable_attributes: {
            id: @account.accountable_id,
            subtype: "auto",
            interest_rate: 4.5,
            term_months: 48,
            rate_type: "fixed",
            initial_balance: 48000
          }
        }
      }
    end

    @account.reload

    assert_equal "Updated Loan", @account.name
    assert_equal 45000, @account.balance
    assert_equal "Updated Bank", @account[:institution_name]
    assert_equal "updatedbank.example", @account[:institution_domain]
    assert_equal "Updated loan notes", @account[:notes]
    assert_equal "auto", @account.accountable.subtype
    assert_equal 4.5, @account.accountable.interest_rate
    assert_equal 48, @account.accountable.term_months
    assert_equal "fixed", @account.accountable.rate_type
    assert_equal 48000, @account.accountable.initial_balance

    assert_redirected_to @account
    assert_equal "Loan account updated", flash[:notice]
    assert_enqueued_with(job: SyncJob)
  end

  test "renders the amortization schedule tab for a fixed rate loan" do
    get account_path(@account, tab: "schedule")

    assert_response :success
    assert_select "table tbody tr", count: @account.loan.term_months
    assert_match "Total Interest", response.body
  end

  # A variable loan IS amortizable since #104, and a provider's own rate type
  # reads as variable since #100 decision 8, so the unamortizable case is now
  # a loan with no rate type at all.
  test "hides the schedule tab when the loan cannot be amortized" do
    @account.loan.update!(rate_type: "")

    get account_path(@account, tab: "schedule")

    assert_response :success
    assert_select "table tbody tr", count: 0
  end

  test "records rate changes and an origination date submitted through the form" do
    patch loan_path(@account), params: {
      account: {
        accountable_attributes: {
          id: @account.loan.id,
          rate_type: "variable",
          start_date: "2024-03-15",
          rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,
          rate_changes: [
            { effective_date: "2026-04-01", rate: "7.25" },
            { effective_date: "2026-10-01", rate: "6.5" },
            { effective_date: "", rate: "" }
          ]
        }
      }
    }

    @account.loan.reload
    assert_equal({ "2026-04-01" => "7.25", "2026-10-01" => "6.5" }, @account.loan.variable_rate_schedule,
      "the wholly blank sentinel row must be dropped rather than persisted or raising")
    assert_equal Date.new(2024, 3, 15), @account.loan.start_date
    assert_equal Date.new(2024, 3, 15), @account.loan.origination_date
  end

  test "the schedule tab reflects a recorded rate change" do
    @account.loan.update!(rate_type: "variable", interest_rate: 6, term_months: 24)

    get account_path(@account, tab: "schedule")
    flat_payments = schedule_table_cells

    # A year into the 24-month term, whatever today is. The fixture loan has no
    # start_date, so its origination moves with the clock; a fixed date would
    # fall before the first payment once the calendar passed it, and the
    # schedule would stop re-amortising.
    change_date = @account.loan.origination_date >> 12
    @account.loan.update!(variable_rate_schedule: { change_date.iso8601 => "18.0" })
    get account_path(@account, tab: "schedule")

    assert_response :success
    # The schedule's own cells, not the whole body: the chart card above the
    # tabs moves for the same change.
    assert_equal flat_payments.length, schedule_table_cells.length
    assert_not_equal flat_payments, schedule_table_cells,
      "recording a rate change must change the payments the schedule tab renders"
    # A substring free of characters ERB escapes -- the full string contains an
    # apostrophe and renders as &#39;.
    assert_match "re-amortises at each recorded change", response.body
    assert_match I18n.t("loans.tabs.schedule.opening_payment"), response.body,
      "a re-amortising schedule must not label its first payment as THE monthly payment"
  end

  # #100 decision 8: a provider writes rate types the form never offers. The
  # select must still carry the loan's own value, or the browser submits the
  # first option and saving any other field turns an "arm" loan into a fixed
  # one without anyone choosing that.
  test "the edit form keeps a provider-written rate type as the selected option" do
    @account.loan.update!(rate_type: "arm")

    get edit_loan_path(@account)

    assert_response :success
    assert_select "select[name='account[accountable_attributes][rate_type]'] option[value='arm'][selected]", { count: 1 },
      "the provider's rate type must be the selected option"
    assert_select "select[name='account[accountable_attributes][rate_type]'] option[value='fixed']", count: 1
    assert_select "[data-loan-rate-changes-fixed-type-value='fixed']", count: 1
  end

  # A term the simulator will not walk leaves the loan without a schedule
  # (see Loan#amortizable?). The model stays tolerant because a provider writes
  # this column too; the form is where a person typing it is told the limit.
  test "the term input declares the range a schedule can be built for" do
    get edit_loan_path(@account)

    assert_response :success
    assert_select "input[name='account[accountable_attributes][term_months]'][min='1'][max='#{Loan::Simulator::MAX_PERIODS}']", count: 1
  end

  # A row with one half filled in is a typo, not a blank. Dropping it silently
  # loses what the user typed between submit and redisplay and never tells them
  # which row went.
  test "a half-filled rate change is rejected rather than silently dropped" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    patch loan_path(@account), params: {
      account: { accountable_attributes: {
        id: @account.loan.id, rate_type: "variable",
        rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,
        rate_changes: [ { effective_date: "", rate: "9" } ]
      } }
    }

    # Asserted on the response, not on a Loan rebuilt in the test: a redirect
    # with the schedule untouched would otherwise pass.
    assert_response :unprocessable_entity
    assert_equal({ "2026-04-01" => "7.25" }, @account.loan.reload.variable_rate_schedule,
      "a rejected submission must not alter the persisted schedule")
    assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", { count: 1 },
      "the typed row comes back so the form can redisplay it"
  end

  # Removing every row must clear the schedule. Without the form's blank
  # sentinel the PATCH carries no rate_changes key at all, nested assignment
  # never calls the writer, and the removed rows stay persisted.
  test "submitting only the blank sentinel clears the schedule" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    # The sentinel is a bare `rate_changes[]=` with no value, which Rack parses
    # as "" and strong parameters drop, so the writer receives an empty array.
    patch loan_path(@account), params: {
      account: { accountable_attributes: {
        id: @account.loan.id, rate_type: "variable", rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,
        rate_changes: [ "" ]
      } }
    }

    assert_empty @account.loan.reload.variable_rate_schedule
  end

  # Reads the payload off the mounted controller's own data attribute rather
  # than parsing rendered SVG paths, which would be a brittle way to assert on
  # data that already has model-level coverage. This test's job is to prove the
  # right payload reaches the browser and mounts the controller.
  def chart_payload
    node = css_select("[data-controller='loan-payoff-chart']").first
    node && JSON.parse(node["data-loan-payoff-chart-data-value"])
  end

  # The chart lives at the top of the account page, inside the chart
  # card's Turbo frame, on whichever tab is open. The Schedule tab keeps its
  # table and cards and no longer carries a chart of its own.
  test "the account page mounts the loan balance chart with its three series" do
    # All three lines need somewhere to be: a period that reaches past today
    # for the forecasts, and a recorded history for the actual line. The
    # earlier intersection assertion here passed with `visible` empty.
    origination = Date.current.prev_year
    @account.loan.update!(start_date: origination)
    @account.balances.create!(date: origination, balance: 500_000, currency: "USD",
                              start_cash_balance: 500_000, flows_factor: -1)
    @account.balances.create!(date: Date.current, balance: 490_000, currency: "USD",
                              start_cash_balance: 490_000, flows_factor: -1)

    get account_path(@account, period: "all_time")

    assert_response :success
    payload = chart_payload
    assert payload["scheduled"].length > 1
    assert payload["projected"].length > 1
    assert_equal %w[actual projected scheduled], payload.fetch("visible").sort
    assert_select "turbo-frame##{ActionView::RecordIdentifier.dom_id(@account, :chart_details)} [data-controller='loan-payoff-chart']", count: 1
    # Owner review of #3474: the chart card carries no data table; the Schedule
    # tab has the figures.
    assert_select "turbo-frame##{ActionView::RecordIdentifier.dom_id(@account, :chart_details)} table", count: 0
  end

  test "the schedule tab renders its table without a chart of its own" do
    get account_path(@account, tab: "schedule")

    assert_response :success
    assert_select "[data-controller='loan-payoff-chart']", { count: 1 }, "one chart on the page, in the chart card"
    assert_select "table", { count: 1 }, "the Schedule tab's table is the only one: the chart has no data table"
  end

  # The what-if left #100's tranche (decision 10) and returns as the Extra
  # repayments tab. An extra adds its own line and moves nothing else: every
  # other series, date and figure is what the page shows without one.
  test "an extra-payment parameter adds the extra line and leaves the rest of the chart as it was" do
    get account_path(@account)
    baseline = chart_payload
    get account_path(@account, extra_payment: { amount: "2000", frequency: "monthly" })

    assert_response :success
    with_extra = chart_payload
    described = %w[visible labels aria_description]
    assert_equal baseline.except(*described), with_extra.except("extra", "extra_payoff_date", *described)
    assert_equal baseline["visible"] + [ "extra" ], with_extra["visible"]
    assert_equal baseline["labels"].merge("extra" => I18n.t("UI.account.chart.loan.extra")), with_extra["labels"]
    # Sentences, not the whole string: #4387 appends the interest/principal
    # share sentence to every description and the what-if sentence lands
    # before it, so a start_with? over the full string fails by construction.
    # The invariant the test means: the extra repayment adds its one sentence
    # and every baseline sentence still appears.
    sentences = ->(d) { d.split(/(?<=\.)\s+/) }
    assert_equal 1, (sentences.(with_extra["aria_description"]) - sentences.(baseline["aria_description"])).size
    assert_empty sentences.(baseline["aria_description"]) - sentences.(with_extra["aria_description"])
  end

  test "a loan with no schedule renders the page without a loan chart" do
    @account.loan.update!(rate_type: "")

    get account_path(@account)

    assert_response :success
    assert_nil chart_payload
    assert_select "[data-controller='time-series-chart']", count: 1
  end
  # The validation lives on Loan and is reached through nested attributes, which
  # validate the nested record only when it has changes. Resubmitting the stored
  # rows plus a typo'd one leaves the column equal to its stored value, so
  # without `Loan#changed_for_autosave?` the account saved with a 302 and the
  # typo'd row vanished.
  test "an invalid row is rejected even when nothing else on the loan changed" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    patch loan_path(@account), params: { account: { accountable_attributes: {
      id: @account.loan.id, rate_type: "variable",
      rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,
      rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" }, { effective_date: "", rate: "9" } ]
    } } }

    assert_response :unprocessable_entity
    assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", { count: 1 },
      "the typed row must come back for correction"
    assert_equal({ "2026-04-01" => "7.25" }, @account.loan.reload.variable_rate_schedule)
  end

  # Retained rows are rendered for a fixed loan too, hidden and disabled, so
  # switching the select to variable reveals them and a save keeps them.
  # Before this, `rate_change_rows` was empty for a fixed loan, the revealed
  # section was empty, and saving sent only the sentinel, which cleared them.
  test "a fixed loan's retained rate changes survive switching to variable and saving" do
    @account.loan.update!(rate_type: "fixed", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    get edit_loan_path(@account)

    assert_response :success
    assert_select "[data-loan-rate-changes-target=rows] [data-rate-change-row]", count: 1
    assert_select "[data-loan-rate-changes-target=rows] input[disabled][value='2026-04-01']", { count: 1 },
      "retained rows are disabled while the loan is fixed, so they are not submitted"

    # What the browser sends after the select is flipped to variable and the
    # inputs are enabled: the sentinel and the row it rendered.
    patch loan_path(@account), params: { account: { accountable_attributes: {
      id: @account.loan.id, rate_type: "variable",
      rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,
      rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" } ]
    } } }

    assert_equal({ "2026-04-01" => "7.25" }, @account.loan.reload.variable_rate_schedule)
    assert_equal "variable", @account.loan.rate_type
  end

  # `disabled` used to be applied only by Stimulus, so without JavaScript the
  # sentinel submitted and the writer read it as "remove them all".
  test "the edit form of a fixed loan disables the whole rate-change section server-side" do
    @account.loan.update!(rate_type: "fixed", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    get edit_loan_path(@account)

    assert_select "[data-loan-rate-changes-target=section][hidden]", count: 1
    assert_select "[data-loan-rate-changes-target=section] input[name='account[accountable_attributes][rate_changes][]'][disabled]", { count: 1 },
      "the sentinel must be disabled too, or a no-JS save clears the schedule"
    # The <template> clone is inert and is left enabled; only rendered rows and
    # the add button are submittable.
    assert_select "[data-loan-rate-changes-target=rows] input:not([disabled])", count: 0
    assert_select "[data-loan-rate-changes-target=rows] button:not([disabled])", count: 0
    assert_select "[data-loan-rate-changes-target=section] button[data-action='loan-rate-changes#add']:not([disabled])", count: 0
  end

  test "a variable loan's edit form enables the rate-change section server-side" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    get edit_loan_path(@account)

    assert_select "[data-loan-rate-changes-target=section][hidden]", count: 0
    assert_select "[data-loan-rate-changes-target=rows] input[disabled]", count: 0
    assert_select "[data-loan-rate-changes-target=section] input[name='account[accountable_attributes][rate_changes][]']:not([disabled])", count: 1
  end

  # The payload runs the schedule, the projection and a balance query on every
  # loan page view, from provider-written and user-written inputs. A raise in
  # any of them must cost the chart, not the page: before this guard the whole
  # account page was a 500 for a loan that rendered fine without the chart.
  test "a chart payload that raises degrades to the time-series chart instead of a 500" do
    Loan::PayoffChart.any_instance.stubs(:payload).raises(ArgumentError, "boom")

    get account_path(@account, tab: "schedule")

    assert_response :success
    assert_select "[data-controller='time-series-chart']", count: 1
    assert_select "[data-controller='loan-payoff-chart']", count: 0
    assert_match "Total Interest", response.body, "the Schedule tab still renders"
  end

  # Owner review of #3474: the rate changes open from a collapsed disclosure,
  # as Additional details does, and the loan's fields keep the form's spacing
  # instead of stacking flush against each other.
  test "the rate changes sit in a collapsed disclosure and the loan fields are spaced" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    get edit_loan_path(@account)

    assert_select "[data-loan-rate-changes-target=section] details:not([open]) > summary", text: /#{I18n.t("loans.form.rate_changes")}/
    assert_select "[data-loan-rate-changes-target=section] details [data-loan-rate-changes-target=rows] input[name$='[rate]'][value='7.25']", count: 1
    assert_select "[data-controller='loan-rate-changes'].space-y-2", count: 1
  end

  # Owner review of #3474: what kind of loan it is belongs with the account's
  # own fields, straight after the balance, before the loan's terms.
  test "the subtype sits under the balance, above the loan's terms" do
    get edit_loan_path(@account)

    body = response.body
    balance = body.index('name="account[balance]"')
    subtype = body.index('name="account[accountable_attributes][subtype]"')
    terms = body.index('name="account[accountable_attributes][initial_balance]"')
    assert balance && subtype && terms, "the balance, subtype and original balance fields must all render"
    assert_operator balance, :<, subtype, "the subtype comes after the balance"
    assert_operator subtype, :<, terms, "the subtype comes before the loan's terms"
  end

  # `Account.create_and_sync` saves with `save!`, and this is the first Loan
  # validation a user can trip from the create form. Without a rescue the
  # request ended on the generic 422 error page and the form was gone.
  test "a half-filled rate change on create re-renders the form instead of the error page" do
    assert_no_difference [ "Account.count", "Loan.count" ] do
      post loans_path, params: { account: {
        name: "Bad Loan", balance: 50_000, currency: "USD", accountable_type: "Loan",
        accountable_attributes: {
          rate_type: "variable", interest_rate: 6, term_months: 12, initial_balance: 50_000,
          rate_changes: [ "", { effective_date: "", rate: "9" } ]
        }
      } }
    end

    assert_response :unprocessable_entity
    assert_select "form[action='#{loans_path}']", count: 1, message: "the new-loan form comes back"
    assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", count: 1
    assert_match "effective date and a rate", response.body
  end

  # The Overview tab quoted `loans.interest_rate`, the origination rate, while
  # the Schedule tab beside it re-amortised at each recorded change.
  test "the overview tab shows the rate in force, not the origination rate" do
    # Drawn down two years ago, so the change a month ago re-sizes a repayment
    # the loan was already making rather than setting its first one.
    @account.loan.update!(rate_type: "variable", interest_rate: 6, start_date: Date.current - 2.years,
                          variable_rate_schedule: { (Date.current - 1.month).iso8601 => "7.25" })

    get account_path(@account, tab: "overview")

    assert_response :success
    assert_select "h4", text: I18n.t("loans.tabs.overview.interest_rate")
    assert_match "7.250%", response.body, "the recorded change is the rate in force"
    assert_no_match "6.000%", response.body, "the origination rate is not what the loan is charging"

    # Owner review of #3474: the repayment card quotes the scheduled repayment
    # in force today -- the next payment on or after it, sized at the rates
    # recorded so far -- rather than N/A.
    schedule = @account.loan.amortization_schedule
    in_force = schedule.payments.find { |payment| payment.date >= Date.current }.payment
    assert_not_equal schedule.periodic_payment, in_force,
      "the fixture must re-amortise before today, or this cannot tell today's repayment from the opening one"
    # Scoped to the card: the Schedule tab's table on the same page lists every
    # payment, so the figure turns up in the body whether or not the card has it.
    card = css_select("h4").find { |title| title.text.strip == I18n.t("loans.tabs.overview.monthly_payment") }&.parent
    assert card, "the overview has a monthly payment card"
    assert_includes card.at_css("p").text,
      ActiveSupport::NumberHelper.number_to_rounded(in_force.amount, precision: 2, delimiter: ","),
      "the card quotes the repayment in force today"
    assert_no_match I18n.t("loans.tabs.overview.not_applicable"), card.text
  end

  test "the overview tab of a fixed loan still shows its rate and monthly payment" do
    @account.loan.update!(rate_type: "fixed", interest_rate: 6, term_months: 360)

    get account_path(@account, tab: "overview")

    assert_response :success
    assert_match "6.000%", response.body
    # 500,000 at 6% over 360 months, the fixture loan's contracted repayment.
    assert_match "2,997.75", response.body
  end

  # The period picker re-renders the chart card's frame, and
  # the cards and the mount must both live inside it.
  test "a chart_details frame request carries the mount and both cards inside the frame" do
    frame_id = ActionView::RecordIdentifier.dom_id(@account, :chart_details)

    get account_path(@account, period: "all_time"), headers: { "Turbo-Frame" => frame_id }

    assert_response :success
    assert_select "turbo-frame##{frame_id} [data-controller='loan-payoff-chart']", count: 1
    assert_select "turbo-frame##{frame_id} h4", text: I18n.t("UI.account.chart.loan.projected_payoff"), count: 1
    assert_select "turbo-frame##{frame_id} h4", text: I18n.t("UI.account.chart.loan.interest_saved"), count: 1
  end

  # The activity feed paginates through its own `entries` frame. That request
  # renders the whole page and keeps one frame, so building the chart payload
  # for it ran a full simulation per page turn for nothing.
  test "a frame request outside the chart card does not build the chart payload" do
    Loan::PayoffChart.any_instance.expects(:payload).never

    get account_path(@account, page: 2), headers: { "Turbo-Frame" => ActionView::RecordIdentifier.dom_id(@account, "entries") }

    assert_response :success
  end

  test "the account's container frame request still builds the chart payload" do
    get account_path(@account, period: "all_time"), headers: { "Turbo-Frame" => ActionView::RecordIdentifier.dom_id(@account, :container) }

    assert_response :success
    assert_select "[data-controller='loan-payoff-chart']", count: 1
  end

  # Owner review of #3474: the Overview cards name the amounts as the loan
  # amount rather than "principal".
  test "the overview tab names the original and remaining loan amounts" do
    get account_path(@account, tab: "overview")

    assert_response :success
    assert_select "h4", text: "Original Loan Amount", count: 1
    assert_select "h4", text: "Remaining Loan Amount", count: 1
    assert_select "h4", text: /Principal/, count: 0
  end

  # Owner review of #3474: the contract's payoff date is one of the loan's
  # terms, so it sits with the others on Overview, named as the original date.
  test "the overview tab shows the original payoff date and the schedule tab does not" do
    payoff_date = @account.loan.amortization_schedule&.payoff_date
    assert payoff_date, "the fixture loan must have a schedule, or there is no date to show"

    get account_path(@account, tab: "overview")

    assert_response :success
    # Both tabs render into the page, so the card is found by its title and
    # placed by the cards beside it.
    card = css_select("h4").find { |title| title.text.strip == "Original Payoff Date" }&.parent
    assert card, "the overview has an original payoff date card"
    assert_equal I18n.l(payoff_date, format: :long), card.at_css("p").text.strip
    assert card.parent.css("h4").any? { |title| title.text.strip == "Original Loan Amount" },
      "the card sits among the Overview cards"
    assert_select "h4", text: "Payoff Date", count: 0
  end

  # Beside the contract's figures, the Schedule tab says
  # when the loan will actually be paid off -- the projection from today's
  # balance that the chart above it draws.
  test "the schedule tab forecasts the payoff date from today's balance" do
    draw_down_loan_two_years_ago
    schedule = @account.loan.amortization_schedule
    scheduled_today = schedule.payments.select { |payment| payment.date <= Date.current }.last
    assert scheduled_today, "the fixture loan must be part-way through its schedule"
    @account.update!(balance: scheduled_today.ending_balance.amount / 2)

    forecast = @account.loan.reload.payoff_projection(as_of: Date.current).payoff_date
    assert forecast, "a loan ahead of schedule has a forecast payoff date"
    assert_operator forecast, :<, schedule.payoff_date,
      "the fixture must be ahead, or this cannot tell the forecast from the original date"

    get account_path(@account, tab: "schedule")

    assert_response :success
    card = css_select("h4").find { |title| title.text.strip == "Forecasted Payoff Date" }&.parent
    assert card, "the schedule tab has a forecasted payoff date card"
    assert_equal I18n.l(forecast, format: :long), card.at_css("p").text.strip
    assert card.parent.css("h4").any? { |title| title.text.strip == "Total Interest" },
      "the card sits among the Schedule cards"
  end

  test "the forecasted payoff date card says when the repayment no longer clears the loan" do
    draw_down_loan_two_years_ago
    @account.update!(balance: @account.loan.original_balance.amount * 10)
    assert_not @account.loan.reload.payoff_projection(as_of: Date.current).converged?,
      "the fixture must be too far behind to clear, or this cannot reach the notice"

    get account_path(@account, tab: "schedule")

    assert_response :success
    card = css_select("h4").find { |title| title.text.strip == "Forecasted Payoff Date" }&.parent
    assert card, "the schedule tab has a forecasted payoff date card"
    assert_equal "Not paid off on the current repayment", card.at_css("p").text.strip
  end

  # Codex on we-promise/sure#3473: `update` persisted the balance change (a
  # valuation and the account's cached balance) before the loan's validation
  # ran, so a rejected form had committed half of itself.
  test "a rejected update does not persist the balance change submitted with it" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })
    balance_before = @account.reload.balance

    assert_no_difference "Entry.count" do
      patch loan_path(@account), params: { account: {
        balance: balance_before - 10_000,
        accountable_attributes: {
          id: @account.loan.id, rate_type: "variable",
          rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,
          rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" }, { effective_date: "", rate: "9" } ]
        }
      } }
    end

    assert_response :unprocessable_entity
    assert_equal balance_before, @account.reload.balance, "the balance half of a rejected form must not commit"
  end

  # CodeRabbit on we-promise/sure#3474: `lock_saved_attributes!` saves with
  # `update!`. Run after the transaction had committed, a raise there left the
  # balance change and the attribute update in place behind a failed request.
  test "an update whose attribute lock fails commits neither the balance nor the attributes" do
    balance_before = @account.reload.balance
    name_before = @account.name
    Account.any_instance.stubs(:lock_saved_attributes!).raises(ActiveRecord::RecordInvalid.new(@account))

    assert_no_difference "Entry.count" do
      patch loan_path(@account), params: { account: { name: "Renamed Loan", balance: balance_before - 10_000 } }
    end

    assert_response :unprocessable_entity
    assert_select "form[action='#{loan_path(@account)}']", count: 1
    assert_equal balance_before, @account.reload.balance, "the balance must roll back with the failed lock"
    assert_equal name_before, @account.name, "the attribute update must roll back with the failed lock"
  end

  test "a successful balance update saves the other submitted values" do
    balance_before = @account.reload.balance
    updated_balance = balance_before - 10_000

    patch loan_path(@account), params: { account: {
      name: "Updated loan name",
      balance: updated_balance,
      accountable_attributes: { id: @account.loan.id, interest_rate: "7.25" }
    } }

    assert_redirected_to account_path(@account)
    assert_equal updated_balance, @account.reload.balance
    assert_equal "Updated loan name", @account.name
    assert_equal BigDecimal("7.25"), @account.loan.reload.interest_rate
  end

  # CodeRabbit on we-promise/sure#3473: a failed balance result exits before
  # the ordinary update path, so the 422 form must still receive the other
  # values the user submitted.
  test "a failed balance update keeps the other submitted values in the form" do
    balance_before = @account.reload.balance
    name_before = @account.name
    rate_before = @account.loan.interest_rate
    failed_balance = Account::CurrentBalanceManager::Result.new(
      success?: false, changes_made?: false, error: "Balance update failed"
    )
    Account.any_instance.stubs(:set_current_balance).returns(failed_balance)

    assert_no_difference "Entry.count" do
      patch loan_path(@account), params: { account: {
        name: "Unsaved loan name",
        notes: "Unsaved loan notes",
        balance: balance_before - 10_000,
        accountable_attributes: { id: @account.loan.id, interest_rate: "7.25" }
      } }
    end

    assert_response :unprocessable_entity
    assert_select "input[name='account[name]'][value='Unsaved loan name']", count: 1
    assert_select "input[name='account[accountable_attributes][interest_rate]'][value='7.25']", count: 1
    assert_match "Balance update failed", response.body
    assert_equal balance_before, @account.reload.balance
    assert_equal name_before, @account.name
    assert_equal rate_before, @account.loan.reload.interest_rate
  end

  # CodeRabbit on we-promise/sure#3473: `loans/new` renders the method
  # selector when `step=method_select`, which reads `@provider_configs`; the
  # rescue path must set it up as `new` does.
  test "a rejected create with the method-select step still renders" do
    post loans_path(step: "method_select"), params: { account: {
      name: "Bad Loan", balance: 50_000, currency: "USD", accountable_type: "Loan",
      accountable_attributes: { rate_type: "variable", interest_rate: 6, term_months: 12, initial_balance: 50_000,
                                rate_changes: [ "", { effective_date: "", rate: "9" } ] }
    } }

    assert_response :unprocessable_entity
  end

  test "the rate-change controls are design-system buttons" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    get edit_loan_path(@account)

    assert_select "button[data-action='loan-rate-changes#add'] span", text: I18n.t("loans.form.rate_change_add")
    assert_select "[data-rate-change-row] button[data-action='loan-rate-changes#remove'] span", text: I18n.t("loans.form.rate_change_remove")
  end

  # The design-system guide asks inputs to take the form's field shape. The rows
  # were bare inputs outside any .form-field, so they rendered with no field
  # border and no visible label. The partial is also the Stimulus clone
  # template, so each label wraps its input rather than pointing at an id that
  # every cloned row would repeat.
  test "each rate-change input is a labelled form field without an id" do
    @account.loan.update!(rate_type: "variable", start_date: Date.new(2026, 1, 1),
                          variable_rate_schedule: { "2026-04-01" => "7.25" })

    get edit_loan_path(@account)

    assert_response :success
    rows = "[data-loan-rate-changes-target=rows] [data-rate-change-row]"
    assert_select "#{rows} .form-field label", count: 2
    assert_select "#{rows} .form-field label input[type=date][value='2026-04-01']", count: 1
    assert_select "#{rows} .form-field label input[type=number][value='7.25']", count: 1
    assert_select "#{rows} .form-field__label", text: I18n.t("loans.form.rate_change_effective_date")
    assert_select "#{rows} .form-field__label", text: I18n.t("loans.form.rate_change_rate")
    # Unscoped on purpose: the <template> copy is the one every added row clones.
    assert_select "[data-rate-change-row] input[id]", count: 0
  end

  # CodeRabbit on we-promise/sure#3473: `create_and_sync` can raise RecordInvalid
  # from the opening valuation's `entries.create!` or from `lock_saved_attributes!`,
  # and then `e.record` is an Entry or the accountable, not the account the form
  # renders.
  test "a create that fails on the opening valuation still re-renders the form" do
    invalid_entry = Entry.new.tap(&:validate)
    Account::OpeningBalanceManager.any_instance.stubs(:set_opening_balance)
      .raises(ActiveRecord::RecordInvalid.new(invalid_entry))

    assert_no_difference "Account.count" do
      post loans_path, params: { account: {
        name: "Loan With Bad Anchor", balance: 50_000, currency: "USD", accountable_type: "Loan",
        accountable_attributes: { rate_type: "fixed", interest_rate: 6, term_months: 12, initial_balance: 50_000 }
      } }
    end

    assert_response :unprocessable_entity
    assert_select "form[action='#{loans_path}']", count: 1
    # Rebuilt from the submission, not a blank account: what was typed comes
    # back for correction.
    assert_select "input[name='account[name]'][value='Loan With Bad Anchor']", count: 1
    assert_select "input[name='account[accountable_attributes][interest_rate]'][value='6']", count: 1
  end

  # The submission that trips this rescue need not carry nested attributes at
  # all. `accountable_type=` writes only the type column, so rebuilding from
  # such a submission left `accountable` nil and the 422 form came back
  # without a single one of the loan's own fields -- nothing for the borrower
  # to correct, on a form whose whole purpose here is correction.
  test "a late create failure renders the loan's fields even when the form sent none" do
    invalid_entry = Entry.new.tap(&:validate)
    Account::OpeningBalanceManager.any_instance.stubs(:set_opening_balance)
      .raises(ActiveRecord::RecordInvalid.new(invalid_entry))

    assert_no_difference "Account.count" do
      post loans_path, params: { account: {
        name: "Loan Without Nested Attributes", balance: 50_000, currency: "USD", accountable_type: "Loan"
      } }
    end

    assert_response :unprocessable_entity
    assert_select "form[action='#{loans_path}']", count: 1
    assert_select "input[name='account[name]'][value='Loan Without Nested Attributes']", count: 1
    assert_select "input[name='account[accountable_attributes][interest_rate]']", minimum: 1
  end

  test "the extra repayments tab shows for a loan that can be amortized, and not otherwise" do
    get account_path(@account)
    assert_select "button[role='tab'][data-id='extra_repayments']", count: 1

    @account.loan.update!(rate_type: "")
    get account_path(@account)
    assert_select "button[role='tab'][data-id='extra_repayments']", count: 0
  end

  test "an extra amount adds the extra's cards and the chart's extra line" do
    get account_path(@account, tab: "extra_repayments")

    assert_response :success
    assert_select "[data-testid='extra-payoff-date']", count: 0
    # With nothing entered, the total is the loan's own, with no saving to quote.
    no_extra = @account.loan.payoff_projection(as_of: Date.current)
    assert_select "[data-testid='total-cost']", text: format_money(no_extra.total_cost)
    assert_select "[data-testid='total-cost-saved']", count: 0
    assert_not_includes chart_payload["visible"], "extra"

    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "500" })

    assert_response :success
    loan = @account.loan.reload
    baseline = loan.payoff_projection(as_of: Date.current)
    extra = loan.payoff_projection(as_of: Date.current, extra: 500)
    assert_select "[data-testid='extra-payoff-date']", text: I18n.l(extra.payoff_date, format: :long)
    assert_select "[data-testid='extra-months-sooner']",
      text: I18n.t("loans.tabs.extra_repayments.months_sooner", count: extra.months_sooner_than(baseline))
    assert_select "[data-testid='extra-interest-saved']", text: format_money(extra.interest_saved_versus(baseline))
    # The third card is the total still to repay with the extra, and how much
    # less that is than paying no extra, over the rest of the loan.
    assert_select "[data-testid='total-cost']", text: format_money(extra.total_cost)
    assert_select "[data-testid='total-cost-saved']",
      text: I18n.t("loans.tabs.extra_repayments.total_cost_saved", amount: format_money(extra.total_cost_saved_versus(baseline)))
    assert_operator extra.total_cost, :<, baseline.total_cost
    assert_select "[data-testid='baseline-payoff-date']", count: 0
    assert_select "input[name='extra_payment[amount]'][value='500.00']", count: 1
    assert_select "select[name='extra_payment[frequency]'] option[selected][value='monthly']", count: 1
    assert_select "[data-testid='extra-dated-note']", count: 0
    assert_includes chart_payload["visible"], "extra"
    assert_equal extra.payoff_date.iso8601, chart_payload["extra_payoff_date"]
  end

  # One reference date for the page: the cards, the tab and the chart all read
  # projections built on the controller's `as_of`, each built once.
  test "the baseline and the extra projections are built once each, on the page's one date" do
    travel_to Time.zone.local(2026, 10, 16, 23, 59, 59) do
      as_of = Date.current
      loan = @account.loan
      baseline = loan.payoff_projection(as_of: as_of)
      extra = loan.payoff_projection(as_of: as_of, extra: BigDecimal("500"))
      Loan.any_instance.expects(:payoff_projection).with(as_of: as_of).once.returns(baseline)
      Loan.any_instance.expects(:payoff_projection).with(as_of: as_of, extra: BigDecimal("500"), extra_frequency: "monthly").once.returns(extra)

      get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "500" })

      assert_response :success
      assert_equal extra.payoff_date.iso8601, chart_payload["extra_payoff_date"]
      assert_select "[data-testid='extra-payoff-date']", text: I18n.l(extra.payoff_date, format: :long)
    end
  end

  # The amount field is a number field, which can hold "-1" but not "abc": the
  # first comes back as typed, the second as an empty field beside the message.
  test "a refused amount shows a message and no extra, keeping what a number field can hold" do
    { "-1" => "input[value='-1.00']", "abc" => "input:not([value])" }.each do |input, kept|
      get account_path(@account, tab: "extra_repayments", extra_payment: { amount: input })

      assert_response :success
      assert_select "[data-testid='extra-amount-error']", text: I18n.t("loans.tabs.extra_repayments.invalid_amount")
      assert_select "#{kept}[name='extra_payment[amount]'][aria-invalid='true']", count: 1
      assert_select "[data-testid='extra-payoff-date']", count: 0
      assert_not_includes chart_payload["visible"], "extra"
    end
  end

  # Weekly extras fall on their own dates, so the figures are the weekly
  # projection's, not the monthly one's, and the tab says how a mid-period
  # extra is counted.
  test "a weekly extra shows the weekly projection's figures, with the choice kept" do
    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "100", frequency: "weekly" })

    assert_response :success
    loan = @account.loan.reload
    baseline = loan.payoff_projection(as_of: Date.current)
    weekly = loan.payoff_projection(as_of: Date.current, extra: 100, extra_frequency: "weekly")
    monthly = loan.payoff_projection(as_of: Date.current, extra: 100)
    assert_not_equal monthly.total_interest, weekly.total_interest, "the fixture must tell weekly from monthly"
    assert_select "[data-testid='extra-interest-saved']", text: format_money(weekly.interest_saved_versus(baseline))
    assert_select "[data-testid='extra-payoff-date']", text: I18n.l(weekly.payoff_date, format: :long)
    assert_select "select[name='extra_payment[frequency]'] option[selected][value='weekly']", count: 1
    assert_select "[data-testid='extra-dated-note']", text: I18n.t("loans.tabs.extra_repayments.dated_note")
  end

  test "a frequency the form does not offer shows a message and no extra" do
    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "100", frequency: "daily" })

    assert_response :success
    assert_select "[data-testid='extra-frequency-error']", text: I18n.t("loans.tabs.extra_repayments.invalid_frequency")
    assert_select "select[name='extra_payment[frequency]'][aria-invalid='true']", count: 1
    assert_select "[data-testid='extra-payoff-date']", count: 0
    assert_not_includes chart_payload["visible"], "extra"
  end

  # The form is built as Sure's other forms are: the shared money field shows
  # the loan's currency, which cannot be changed here (and so is not
  # submitted), and how often is a select of the three choices.
  test "the extra repayments form uses the money field and a frequency select" do
    get account_path(@account, tab: "extra_repayments")

    assert_select "form[method='get'] [data-controller='money-field']" do
      assert_select "[data-money-field-target='symbol']", text: Money::Currency.new(@account.currency).symbol
      assert_select "select[name='extra_payment[currency]'][disabled]", count: 1
    end
    assert_select "select[name='extra_payment[frequency]'] option",
      count: 3, text: /#{%w[weekly fortnightly monthly].map { |f| I18n.t("loans.tabs.extra_repayments.frequencies.#{f}") }.join("|")}/
  end

  test "a zero or blank amount shows no extra and no message" do
    [ "0", "" ].each do |input|
      get account_path(@account, tab: "extra_repayments", extra_payment: { amount: input })

      assert_response :success
      assert_select "[data-testid='extra-amount-error']", count: 0
      assert_select "[data-testid='extra-payoff-date']", count: 0
      assert_not_includes chart_payload["visible"], "extra"
    end
  end

  # The params are the borrower's to shape. A scalar where the form sends a
  # hash, or an array where it sends a scalar, is no extra rather than a 500.
  test "extra repayment params of the wrong shape are ignored" do
    get account_path(@account, tab: "extra_repayments", extra_payment: "500")
    assert_response :success
    assert_select "[data-testid='extra-payoff-date']", count: 0

    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: [ "500" ] })
    assert_response :success
    assert_select "[data-testid='extra-payoff-date']", count: 0
  end

  # A balance the current repayment never clears has no payoff date, so there
  # is no "months sooner" or "interest saved" to quote. The tab gives the
  # extra's own date and says why the comparison is missing.
  test "when only the extra clears the loan, the tab gives its date and says the repayment alone never does" do
    draw_down_loan_two_years_ago
    @account.update!(balance: 600_000)
    loan = @account.loan.reload
    baseline = loan.payoff_projection(as_of: Date.current)
    extra = loan.payoff_projection(as_of: Date.current, extra: 5_000)
    assert_not baseline.converged?, "the fixture must be too far behind to clear"
    assert extra.converged?, "and the extra must clear it"

    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "5000" })

    assert_response :success
    assert_select "[data-testid='extra-payoff-date']", text: I18n.l(extra.payoff_date, format: :long)
    assert_select "[data-testid='extra-months-sooner']", count: 0
    assert_select "[data-testid='extra-interest-saved']", count: 0
    assert_select "[data-testid='baseline-not-cleared']",
      text: I18n.t("loans.tabs.extra_repayments.baseline_not_cleared", balloon: format_money(baseline.balloon_amount))
  end

  test "an extra too small to clear the loan says so instead of quoting a date" do
    draw_down_loan_two_years_ago
    @account.update!(balance: 600_000)

    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "1" })

    assert_response :success
    assert_select "[data-testid='extra-payoff-date']", count: 0
    assert_select "[data-testid='extra-not-cleared']", text: I18n.t("loans.tabs.extra_repayments.extra_not_cleared")
  end

  # The design system's form actions: one action is the form's full-width
  # primary submit; Clear and Apply are a right-aligned pair, Clear first as
  # a ghost link and Apply the primary submit.
  test "the extra repayments form ends in the design system's form actions" do
    clear_href = account_path(@account, tab: "extra_repayments")
    form = "form#extra_repayments_form[method='get']"

    get account_path(@account, tab: "extra_repayments")
    assert_select "#{form} button[type='submit']", count: 1 do |buttons|
      assert_includes buttons.first["class"], "w-full", "a single action is full width"
      assert_includes buttons.first["class"], "bg-inverse", "and primary, not outline"
    end
    assert_select "#{form} a[href='#{clear_href}']", count: 0

    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "500" })
    assert_select "#{form} div.justify-end", count: 1 do
      assert_select "> a[href='#{clear_href}'] + button[type='submit']", count: 1
    end
    assert_select "#{form} button[type='submit']", count: 1 do |buttons|
      assert_not_includes buttons.first["class"], "w-full", "a pair keeps natural widths"
      assert_includes buttons.first["class"], "bg-inverse", "Apply stays the primary"
    end
  end

  # The tab says why there is nothing to model. A repaid loan has nothing
  # left to repay; a loan past its last scheduled repayment with a balance
  # still owing has no repayment to add an extra to, and must not be told
  # it is repaid.
  test "the extra repayments tab tells a repaid loan from one past maturity with a balance owing" do
    # The opening valuation keeps the loan amortizable, and so its tab shown,
    # once the balance is zero.
    draw_down_loan_two_years_ago
    @account.update_columns(balance: 0)
    assert @account.loan.reload.amortizable?, "the tab must still be offered"
    get account_path(@account, tab: "extra_repayments")

    assert_response :success
    assert_select "[data-testid='extra-not-applicable']", text: I18n.t("loans.tabs.extra_repayments.not_applicable")
    assert_select "input[name='extra_payment[amount]']", count: 0

    @account.update_columns(balance: 500_000)
    @account.loan.update!(start_date: Date.current - 3.years, term_months: 24)
    assert_not @account.loan.reload.payoff_projection(as_of: Date.current).applicable?, "the fixture must be past maturity"
    get account_path(@account, tab: "extra_repayments")

    assert_response :success
    assert_select "[data-testid='extra-not-applicable']", text: I18n.t("loans.tabs.extra_repayments.no_scheduled_repayments")
    assert_select "input[name='extra_payment[amount]']", count: 0
  end

  # The page rebuilds an extra only from its params, and picking a chart
  # period reloads the page. Each period link carries the applied extra and
  # the tab it was applied from, so the extra line, the cards and the tab
  # survive the pick.
  test "the chart's period links keep an applied extra and its tab" do
    get account_path(@account, tab: "extra_repayments", extra_payment: { amount: "100", frequency: "weekly" })

    assert_response :success
    queries = period_link_queries
    assert_not_empty queries
    queries.each do |query|
      assert_equal({ "amount" => "100", "frequency" => "weekly" }, query["extra_payment"])
      assert_equal "extra_repayments", query["tab"]
    end
  end

  # Nothing to keep: no amount, a zero or a refused one. The links stay as
  # they were before the tab existed, a period and nothing else.
  test "the chart's period links carry nothing when no extra applies" do
    [ nil, { amount: "0" }, { amount: "abc" }, { amount: "100", frequency: "daily" } ].each do |extra_payment|
      get account_path(@account, tab: "extra_repayments", extra_payment: extra_payment)

      assert_response :success
      queries = period_link_queries
      assert_not_empty queries
      queries.each { |query| assert_equal [ "period" ], query.keys, "for #{extra_payment.inspect}" }
    end
  end

  private
    # The query of every period link in the chart card's picker.
    def period_link_queries
      chart_card = "##{ActionView::RecordIdentifier.dom_id(@account, :chart)}"
      css_select("#{chart_card} a[href*='period=']").map { |link| Rack::Utils.parse_nested_query(URI(link["href"]).query) }
    end

    # Posts the new-loan form as a browser does: the "Opening balance date"
    # field is always sent, defaulting to today minus two years.
    def create_loan(start_date:, initial_balance: 400_000, opening_balance_date: Date.current - 2.years)
      post loans_path, params: {
        account: {
          name: "Mortgage",
          balance: 399_600,
          currency: "USD",
          accountable_type: "Loan",
          opening_balance_date: opening_balance_date.iso8601,
          accountable_attributes: {
            subtype: "mortgage",
            interest_rate: 5,
            term_months: 360,
            rate_type: "fixed",
            initial_balance: initial_balance,
            start_date: start_date&.iso8601
          }
        }
      }
      account = Account.order(:created_at).last
      assert_redirected_to account
      account
    end

    # The payment cells of the Schedule tab's table, the only table on the page.
    def schedule_table_cells
      css_select("table tbody td").map { |cell| cell.text.strip }
    end

    # The fixture loan starts today with no opening valuation. Drawn down two
    # years ago, it has payments behind it; with the valuation the account form
    # records, its principal stays the amount borrowed when a test then moves
    # the balance -- without one the schedule would amortise the new balance.
    def draw_down_loan_two_years_ago
      start_date = Date.current - 2.years
      @account.loan.update!(start_date: start_date)
      @account.entries.create!(
        date: start_date, name: "Opening balance", amount: @account.balance, currency: @account.currency,
        entryable: Valuation.new(kind: "opening_anchor")
      )
    end

    # The figure under every summary card titled exactly `title`, in page order.
    def card_values(title)
      css_select("h4").select { |h4| h4.text.strip == title }.map { |h4| h4.next_element.text.strip }
    end

    def format_money(money)
      ApplicationController.helpers.format_money(money)
    end
end