Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
88.7 KB
Raw Blame
require "test_helper"

class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTest
  include FamilyLockTestHelper
  include ActiveJob::TestHelper

  setup do
    sign_in @user = users(:family_admin)
    # The declare/edit/suggestion paths sit behind the Bills preview gate.
    @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
    @family = @user.family
    @recurring_transaction = recurring_transactions(:netflix_subscription)
    ensure_tailwind_build
  end

  # How often is one of the four things anyone needs to add a bill, and it used
  # to render below the payment link and the autopay toggle: the fourth
  # essential field sat under two most people never set.
  test "the add form leads with the essentials and tucks the rest away" do
    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    body = response.body

    name_at = body.index("recurring_transaction[name]")
    amount_at = body.index("recurring_transaction[amount]")
    due_at = body.index("recurring_transaction[first_due_on]")
    often_at = body.index("recurring_transaction[frequency_preset]")
    url_at = body.index("recurring_transaction[payment_url]")

    assert name_at && amount_at && due_at && often_at && url_at
    assert_operator name_at, :<, amount_at
    assert_operator amount_at, :<, due_at
    assert_operator due_at, :<, often_at, "how often belongs with the essentials"
    assert_operator often_at, :<, url_at, "and above the advanced fields, not below them"

    # Tucked away is not the same as gone.
    assert_match "recurring_transaction[autopay]", body
    assert_match "recurring_transaction[notes]", body
    assert_match I18n.t("recurring_transactions.form.more_options"), body
    assert_match I18n.t("recurring_transactions.frequency_presets.once"), body
    assert_match I18n.t("recurring_transactions.form.once_new_hint"), body
  end

  # The amount is the money field every other form uses. On a new bill its
  # currency is picked there, defaulting to the family's, or the transaction's
  # when the dialog starts from one. On an existing bill it shows and stays.
  test "the add and edit forms use the app's money field and category select" do
    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_select ".form-field[data-controller~='money-field'] input[name=?]", "recurring_transaction[amount]"
    # Blurred in privacy mode, and still typeable.
    assert_select "input.privacy-sensitive.privacy-sensitive-interactive[name=?]", "recurring_transaction[amount]"
    assert_select "select[name=?]:not([disabled]) option[selected][value=?]", "recurring_transaction[currency]", @family.currency
    # The candidate list's rows are divided by a real token: divide-divider
    # matched nothing, so its rules fell back to the text colour.
    assert_no_match "divide-divider", response.body

    entry = accounts(:depository).entries.create!(date: Date.current - 20, amount: 12.5, currency: "EUR",
                                                  name: "STREAMBOX", entryable: Transaction.new)
    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }
    assert_select "select[name=?] option[selected][value=?]", "recurring_transaction[currency]", "EUR"
    assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "12.50"

    get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }
    assert_select "select[name=?][disabled] option[selected][value=?]", "recurring_transaction[currency]", @recurring_transaction.currency
    assert_select "#category_id_trigger"
    assert_select "input[type=hidden][name=?]", "recurring_transaction[category_id]"
  end

  # The bill form's category picker groups a category under its parent and
  # finds one by name, the way the transaction form's picker does. A flat list
  # of every category puts a subcategory among unrelated neighbours, and a
  # family with many categories has to scroll to find one.
  test "the bill edit form groups categories under their parent and searches them" do
    get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }

    assert_response :success

    # The picker searches, so a category is found by name, not by scrolling.
    assert_select "input[type=search][data-category-select-target=?]", "search"

    names = css_select("[data-category-select-target=option]").map { |option| option["data-category-name"] }
    parent = categories(:food_and_drink).name
    child = categories(:subcategory).name

    assert_includes names, parent
    assert_includes names, child
    assert_operator names.index(parent), :<, names.index(child), "a subcategory follows its parent"

    # The child row says so, so the order reads as a hierarchy and not as an
    # alphabetical accident.
    assert_select "[data-category-name=?] [data-testid=?]", child, "category-select-subcategory-indicator"
  end

  # A family that locked its categories cannot create one, whichever form it
  # starts from. The bill form used to offer the create row anyway.
  test "the bill edit form does not offer to create categories when the family locked them" do
    @family.update!(categories_locked: true)

    get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_select "[data-category-select-locked-value=?]", "true"
  end

  # Assigning the amount would already round it to the column's four places,
  # so the edit form refuses a finer one instead of saving a different figure.
  test "update refuses an amount finer than the column keeps" do
    patch recurring_transaction_url(@recurring_transaction),
      params: { recurring_transaction: { name: @recurring_transaction.display_name, amount: "15.123456" } }

    assert_response :unprocessable_entity
    assert_match I18n.t("recurring_transactions.create.amount_too_precise"), response.body
    assert_equal 15.99, @recurring_transaction.reload.amount
  end

  # Editing the amount is how a rent rise is declared, so the old price has to
  # stay in history for anything comparing against an earlier date.
  test "update keeps the previous amount in the bill's price history" do
    patch recurring_transaction_url(@recurring_transaction),
      params: { recurring_transaction: { name: @recurring_transaction.display_name, amount: "17.99" } }

    @recurring_transaction.reload
    assert_equal 17.99, @recurring_transaction.amount
    assert_equal 15.99, @recurring_transaction.amount_on(6.months.ago.to_date)
    assert @recurring_transaction.recurring_price_changes.sole.recorded_by_user?
  end

  test "the amount steps by the currency, never finer than the column" do
    assert_in_delta 0.01, RecurringTransaction.amount_step("USD")
    assert_in_delta 1.0, RecurringTransaction.amount_step("JPY")
    assert_in_delta 0.0001, RecurringTransaction.amount_step("BTC")

    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }
    assert_select "input[name=?][step=?]", "recurring_transaction[amount]", "0.01"
  end

  test "create keeps the currency picked on the form" do
    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "Streambox", amount: "12.50", currency: "EUR",
        account_id: accounts(:depository).id, first_due_on: (Date.current + 9).iso8601,
        frequency_preset: "monthly"
      }
    }

    bill = @family.recurring_transactions.find_by!(name: "Streambox")
    assert_equal "EUR", bill.currency
    assert_equal 12.5, bill.amount
  end

  test "edit renders the form" do
    get edit_recurring_transaction_url(@recurring_transaction)

    assert_response :success
  end

  # These three mutate: identify runs the whole detection and matching
  # pipeline, cleanup destroys stale series, and toggle_status pauses a bill,
  # which deletes its future occurrences. A GET route puts all of that behind a
  # plain URL, outside CSRF protection, where an image tag on any page a signed
  # in user visits is enough to fire it.
  test "the mutating actions refuse GET" do
    paths = {
      "/recurring_transactions/identify" => :get,
      "/recurring_transactions/cleanup" => :get,
      "/recurring_transactions/#{@recurring_transaction.id}/toggle_status" => :get
    }

    paths.each do |path, verb|
      assert_raises(ActionController::RoutingError, "#{path} must not answer #{verb.to_s.upcase}") do
        Rails.application.routes.recognize_path(path, method: verb)
      end
    end
  end

  test "identify runs the pipeline over POST" do
    post identify_recurring_transactions_url

    assert_redirected_to recurring_transactions_url
  end

  test "cleanup retires stale series over POST" do
    post cleanup_recurring_transactions_url

    assert_redirected_to recurring_transactions_url
  end

  test "toggle_status pauses and resumes over POST" do
    assert @recurring_transaction.active?

    post toggle_status_recurring_transaction_url(@recurring_transaction)
    assert_not @recurring_transaction.reload.active?

    post toggle_status_recurring_transaction_url(@recurring_transaction)
    assert @recurring_transaction.reload.active?
  end

  # Pause is offered from the Bills drawer and the bill's page as well as from
  # this settings page, and it used to send all of them here.
  test "toggle_status returns to the page it was pressed on" do
    post toggle_status_recurring_transaction_url(@recurring_transaction), headers: { "Referer" => bills_url }

    assert_redirected_to bills_url
  end

  # The dialog is delivered into the shared <turbo-frame id="modal"> that every page
  # layout already renders empty. If this action responds with a full page layout,
  # the response carries two frames with that id, Turbo matches the empty one first,
  # and the pencil icon silently does nothing. Assert there is exactly one.
  test "edit responds to a turbo frame request with a single modal frame" do
    get edit_recurring_transaction_url(@recurring_transaction),
        headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_equal 1, response.body.scan(/<turbo-frame[^>]*id="modal"/).size
  end

  test "a failed update still renders a single modal frame" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { payment_url: "javascript:alert(1)" } },
          headers: { "Turbo-Frame" => "modal" }

    assert_response :unprocessable_entity
    assert_equal 1, response.body.scan(/<turbo-frame[^>]*id="modal"/).size
  end

  test "update saves a payment link" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { payment_url: "pay.example.com/bill" } }

    assert_redirected_to recurring_transactions_url
    assert_equal "https://pay.example.com/bill", @recurring_transaction.reload.payment_url
  end

  test "update saves and clears a bank reference" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { bank_reference: "VN 4711" } }
    assert_equal "VN 4711", @recurring_transaction.reload.bank_reference

    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { bank_reference: "" } }
    assert_nil @recurring_transaction.reload.bank_reference
  end

  test "update toggles match by reference only" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { bank_reference: "VN 4711", reference_only: "1" } }
    assert @recurring_transaction.reload.reference_only?

    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { bank_reference: "VN 4711", reference_only: "0" } }
    assert_not @recurring_transaction.reload.reference_only?
  end

  test "edit offers the bank reference field" do
    get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }

    assert_match "recurring_transaction[bank_reference]", response.body
    assert_match "recurring_transaction[reference_only]", response.body
  end

  test "new renders the create dialog in a single modal frame" do
    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_equal 1, response.body.scan(/<turbo-frame[^>]*id="modal"/).size
  end

  test "add income opens an income dialog, not a bill dialog" do
    get new_recurring_transaction_url(income: true), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.income_title"), response.body
    assert_match I18n.t("recurring_transactions.form.income_name_label"), response.body
    assert_match I18n.t("recurring_transactions.form.submit_income"), response.body
    # Nothing bill-shaped survives in income mode.
    assert_no_match I18n.t("recurring_transactions.form.autopay_hint"), response.body
    assert_no_match I18n.t("recurring_transactions.form.payment_url_label"), response.body
    assert_no_match I18n.t("recurring_transactions.form.submit"), response.body
  end

  test "fresh bill dialog offers detected recurring charges as starting points" do
    account = accounts(:depository)
    2.times do |i|
      account.entries.create!(
        date: Date.current - ((i + 1) * 30).days,
        amount: 45.00, currency: "USD", name: "City Water",
        entryable: Transaction.new
      )
    end

    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.start_from_title"), response.body
    assert_match "City Water", response.body
  end

  test "the candidate strip never offers a pattern on an account the member cannot reach" do
    3.times do |i|
      accounts(:investment).entries.create!(
        date: Date.current - ((i + 1) * 30).days,
        amount: 45.00, currency: "USD", name: "PRIVATE BROKERAGE SUB",
        entryable: Transaction.new
      )
    end
    member = users(:family_member)
    member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))
    sign_in member

    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_no_match "PRIVATE BROKERAGE SUB", response.body
  end

  test "income dialog offers only detected deposits" do
    account = accounts(:depository)
    2.times do |i|
      account.entries.create!(
        date: (i + 1).months.ago.beginning_of_month + 2.days,
        amount: -1840.00, currency: "USD", name: "ACME PAYROLL",
        entryable: Transaction.new
      )
      account.entries.create!(
        date: Date.current - ((i + 1) * 30).days,
        amount: 45.00, currency: "USD", name: "City Water",
        entryable: Transaction.new
      )
    end

    get new_recurring_transaction_url(income: true), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.start_from_income_title"), response.body
    assert_match "ACME PAYROLL", response.body
    assert_no_match "City Water", response.body
  end

  test "prefilled dialog hides the picker" do
    account = accounts(:depository)
    entries = 2.times.map do |i|
      account.entries.create!(
        date: Date.current - ((i + 1) * 30).days,
        amount: 45.00, currency: "USD", name: "City Water",
        entryable: Transaction.new
      )
    end

    get new_recurring_transaction_url(entry_id: entries.last.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_no_match I18n.t("recurring_transactions.new.start_from_title"), response.body
  end

  test "new prefills from a transaction" do
    entry = accounts(:depository).entries.create!(
      date: Date.current - 20, amount: 184.37, currency: "USD", name: "PG&E WEB PAYMENT",
      entryable: Transaction.new
    )

    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match "PG&amp;E WEB PAYMENT", response.body
    assert_match "184.37", response.body
  end

  test "new prefills the category of the transaction it starts from" do
    entry = accounts(:depository).entries.create!(
      date: Date.current - 20, amount: 54.73, currency: "USD", name: "PET COVER",
      entryable: Transaction.new(category: categories(:food_and_drink))
    )

    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_select "input[name=?][value=?]", "recurring_transaction[category_id]", categories(:food_and_drink).id
  end

  # CategoriesController refuses to create a category while they are locked,
  # so neither bill form may offer inline creation then. The flag is read by
  # the category-select controller from this data attribute.
  test "the add and edit category selects follow the family's category lock" do
    entry = accounts(:depository).entries.create!(
      date: Date.current - 20, amount: 54.73, currency: "USD", name: "PET COVER",
      entryable: Transaction.new(category: categories(:food_and_drink))
    )
    locked_select = "[data-category-select-locked-value=?]"

    [ false, true ].each do |locked|
      @family.update!(categories_locked: locked)

      get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }
      assert_select locked_select, locked.to_s, count: 1

      get edit_recurring_transaction_url(@recurring_transaction), headers: { "Turbo-Frame" => "modal" }
      assert_select locked_select, locked.to_s, count: 1
    end
  end

  test "new offers no category for a paycheck" do
    entry = accounts(:depository).entries.create!(
      date: Date.current - 10, amount: -1840, currency: "USD", name: "ACME PAYROLL",
      entryable: Transaction.new(category: categories(:income))
    )

    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_select "[name=?]", "recurring_transaction[category_id]", count: 0
  end

  # Sharing is per account, so a family scope is not an access check. Prefilling
  # reads the entry's name, amount and account straight back into the form.
  test "new ignores a transaction from an account the user was never given" do
    hidden = accounts(:investment).entries.create!(
      date: Date.current - 3, amount: 622.41, currency: "USD", name: "PRIVATE BROKERAGE FEE",
      entryable: Transaction.new
    )
    member = users(:family_member)
    member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))
    sign_in member

    get new_recurring_transaction_url(entry_id: hidden.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_no_match "PRIVATE BROKERAGE FEE", response.body
    assert_no_match "622.41", response.body
  end

  test "prefilling from an inflow pre-selects income" do
    entry = accounts(:depository).entries.create!(
      date: Date.current - 10, amount: -1840, currency: "USD", name: "ACME PAYROLL",
      entryable: Transaction.new
    )

    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.income_title"), response.body
  end

  test "editing income keeps bill wording out of the dialog" do
    payday = Date.current + 3
    income = @family.recurring_transactions.create!(
      name: "Paycheck", account: accounts(:depository), amount: -1840, currency: "USD",
      bill_type: "income", expected_day_of_month: payday.day, anchor_date: payday,
      last_occurrence_date: payday, next_expected_date: payday, status: "active", manual: true
    )

    get edit_recurring_transaction_url(income), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.edit.income_title", name: "Paycheck"), response.body
    # Apostrophes HTML-escape in the body, so match on stable fragments.
    assert_match "match your payday", response.body
    assert_no_match(/comes due/, response.body)
  end

  test "removing a bill never touches the ledger and lands back on bills" do
    due = Date.current + 5
    bill = @family.recurring_transactions.create!(
      name: "City Water", account: accounts(:depository), amount: 45, currency: "USD",
      expected_day_of_month: due.day, anchor_date: due, last_occurrence_date: due,
      next_expected_date: due, status: "active", manual: true
    )
    RecurringTransaction::OccurrenceGenerator.new(bill).generate!
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: 45, currency: "USD", name: "CITY WATER",
      entryable: Transaction.new
    )
    occurrence = bill.recurring_occurrences.order(:due_on).first
    RecurringTransaction::Allocator.new(occurrence).allocate!(amount: "45", entry: entry)

    delete recurring_transaction_url(bill), headers: { "HTTP_REFERER" => bills_url }

    assert_redirected_to bills_url
    assert_equal I18n.t("recurring_transactions.deleted"), flash[:notice]
    assert Entry.exists?(entry.id), "removing a bill must never delete ledger entries"
  end

  # A bill visited at its own URL opens in the drawer over the overview, so
  # going back there after removing it would reopen it, or 404 on it.
  test "deleting a bill from its own URL lands on the overview" do
    bill = @family.recurring_transactions.create!(
      name: "City Water", account: accounts(:depository), amount: 45, currency: "USD",
      expected_day_of_month: 5, last_occurrence_date: 1.month.ago.to_date,
      next_expected_date: Date.current, status: "active", manual: true
    )

    delete recurring_transaction_url(bill), headers: { "HTTP_REFERER" => bill_url(bill) }

    assert_redirected_to bills_url
  end

  # Which kind this is was settled by the entry point that opened the dialog.
  # The checkbox asked it again, and ticking it reshaped nothing: you filled in
  # bill-shaped labels, pressed Save bill, and got an income record.
  test "the add-bill dialog does not offer to make it income" do
    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_no_match(/name="recurring_transaction\[is_income\]"/, response.body)
  end

  test "the add-income dialog carries the answer without asking" do
    get new_recurring_transaction_url(income: true), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match(/type="hidden"[^>]*name="recurring_transaction\[is_income\]"/, response.body)
    assert_no_match(/type="checkbox"[^>]*name="recurring_transaction\[is_income\]"/, response.body)
  end

  # Reported upstream: a deleted auto-detected recurring transaction comes back
  # on the next detection run, so users delete the same row over and over. The
  # pattern is still in the bank data, so a hard delete only lasts until the
  # next sync. Removing it leaves the same `ended` tombstone that dismissing a
  # suggestion does, and the Identifier refuses to claim or recreate one.
  test "a deleted detected bill does not come back on the next detection run" do
    account = accounts(:depository)
    anchor_day = Date.current.beginning_of_month + 8
    3.times do |i|
      account.entries.create!(
        date: anchor_day - i.months, amount: 42.00, currency: "USD",
        name: "City Water", entryable: Transaction.create!(category: categories(:food_and_drink))
      )
    end

    RecurringTransaction::Identifier.new(@family).identify_recurring_patterns
    detected = @family.recurring_transactions.find_by(name: "City Water")
    assert_not_nil detected
    assert_not detected.manual?

    delete recurring_transaction_url(detected)

    RecurringTransaction::Identifier.new(Family.find(@family.id)).identify_recurring_patterns

    rows = @family.recurring_transactions.where(name: "City Water")
    assert_equal 1, rows.count, "detection must not build a second row for a pattern the user removed"
    assert_equal "ended", rows.first.status, "and the one that remains is a tombstone, not a live bill"
    assert_empty @family.recurring_transactions.where(name: "City Water").where.not(status: "ended")
  end

  # A hand-declared bill has no pattern behind it, so nothing would bring it
  # back and it is deleted outright rather than left lying around as ended.
  test "a declared bill is deleted outright" do
    bill = @family.recurring_transactions.create!(
      name: "Typo Bill", account: accounts(:depository), amount: 10, currency: "USD",
      dedup_scope: "typo", bill_type: "bill", expected_day_of_month: Date.current.day,
      anchor_date: Date.current, last_occurrence_date: Date.current,
      next_expected_date: Date.current, status: "active", manual: true
    )

    assert_difference "@family.recurring_transactions.count", -1 do
      delete recurring_transaction_url(bill)
    end
  end

  test "creating income says income, not bill" do
    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "Paycheck",
        amount: "1840",
        account_id: accounts(:depository).id,
        first_due_on: (Date.current + 3).iso8601,
        frequency_preset: "biweekly",
        is_income: "1"
      }
    }

    assert_equal I18n.t("recurring_transactions.create.success_income"), flash[:notice]
  end

  test "create declares a manual bill and materializes its occurrences" do
    due = Date.current + 16

    assert_difference "@family.recurring_transactions.count", 1 do
      post recurring_transactions_url, params: {
        recurring_transaction: {
          name: "Watson Property",
          amount: "2150",
          account_id: accounts(:depository).id,
          first_due_on: due.iso8601,
          frequency_preset: "monthly"
        }
      }
    end

    bill = @family.recurring_transactions.order(:created_at).last
    assert bill.manual?
    assert_equal "active", bill.status
    assert_equal 2150, bill.amount
    assert_equal due.day, bill.expected_day_of_month
    assert_equal due, bill.anchor_date
    # Monthly on the derived day IS the zero-rule implicit shape, so no
    # redundant rule row is written; the detection reads it back correctly.
    detection = RecurringTransaction::FrequencyPreset.detect(bill)
    assert_equal "monthly", detection.key
    assert_equal due.day, detection.day_of_month
    assert bill.recurring_occurrences.reload.exists?(due_on: due),
           "the declared bill's occurrence must materialize immediately"
  end

  test "create keeps the category chosen on the add form" do
    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "Pet Cover", amount: "54.73", account_id: accounts(:depository).id,
        first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",
        category_id: categories(:food_and_drink).id
      }
    }

    assert_redirected_to bills_path
    assert_equal categories(:food_and_drink), @family.recurring_transactions.order(:created_at).last.category
  end

  test "create leaves a declared paycheck uncategorised" do
    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "Acme Payroll", amount: "1840", account_id: accounts(:depository).id, is_income: "1",
        first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",
        category_id: categories(:income).id
      }
    }

    bill = @family.recurring_transactions.order(:created_at).last
    assert_equal "Acme Payroll", bill.name
    assert bill.typed_income?
    assert_nil bill.category_id
  end

  test "create rejects another family's category" do
    foreign = families(:empty).categories.create!(name: "Foreign Category")

    assert_no_difference "@family.recurring_transactions.count" do
      post recurring_transactions_url, params: {
        recurring_transaction: {
          name: "Pet Cover", amount: "54.73", account_id: accounts(:depository).id,
          first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",
          category_id: foreign.id
        }
      }
    end

    assert_response :unprocessable_entity
  end

  # The uuid column casts a malformed id to nil, which the ownership validation
  # then skips, so without its own check the bill saved uncategorised.
  test "create rejects a category id that is not an id" do
    assert_no_difference "@family.recurring_transactions.count" do
      post recurring_transactions_url, params: {
        recurring_transaction: {
          name: "Pet Cover", amount: "54.73", account_id: accounts(:depository).id,
          first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",
          category_id: "not-a-category"
        }
      }
    end

    assert_response :unprocessable_entity
    assert_match I18n.t("recurring_transactions.create.category_invalid"), response.body
  end

  # A paycheck never takes a category, so whatever was posted for one is
  # ignored rather than refused.
  test "create ignores a malformed category id on a declared paycheck" do
    assert_difference "@family.recurring_transactions.count", 1 do
      post recurring_transactions_url, params: {
        recurring_transaction: {
          name: "Acme Payroll", amount: "1840", account_id: accounts(:depository).id, is_income: "1",
          first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly",
          category_id: "not-a-category"
        }
      }
    end

    assert_nil @family.recurring_transactions.order(:created_at).last.category_id
  end

  test "create with a non-monthly preset writes explicit rules" do
    due = Date.current + 4

    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "Cleaning service", amount: "80", account_id: accounts(:depository).id,
        first_due_on: due.iso8601, frequency_preset: "biweekly"
      }
    }

    bill = @family.recurring_transactions.order(:created_at).last
    rule = bill.recurrence_rules.sole
    assert_equal [ "weekly", 2, due.wday ], [ rule.frequency, rule.interval, rule.weekday ]
    assert_equal due, bill.anchor_date
  end

  test "create with a custom interval takes its day from the due date" do
    due = Date.current + 4

    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "Haircut", amount: "16", account_id: accounts(:depository).id,
        first_due_on: due.iso8601, frequency_preset: "interval",
        frequency_interval: "3", frequency_interval_unit: "weekly"
      }
    }

    bill = @family.recurring_transactions.order(:created_at).last
    rule = bill.recurrence_rules.sole
    assert_equal [ "weekly", 3, due.wday ], [ rule.frequency, rule.interval, rule.weekday ]
    assert_equal due, bill.anchor_date
  end

  test "create without a due date re-renders with an error" do
    assert_no_difference "@family.recurring_transactions.count" do
      post recurring_transactions_url, params: {
        recurring_transaction: { name: "No date", amount: "10", frequency_preset: "monthly", first_due_on: "" }
      }
    end

    assert_response :unprocessable_entity
  end

  test "create with a currency-formatted amount re-renders with an error instead of crashing" do
    assert_no_difference "@family.recurring_transactions.count" do
      post recurring_transactions_url, params: {
        recurring_transaction: { name: "Trash Pickup", amount: "$40.00", account_id: accounts(:depository).id,
                                 first_due_on: (Date.current + 5).iso8601, frequency_preset: "monthly" }
      }
    end

    assert_response :unprocessable_entity
    assert_match I18n.t("recurring_transactions.create.amount_invalid"), response.body
  end

  test "update with an unresolvable account keeps the current account and reports the error" do
    original_account_id = @recurring_transaction.account_id

    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { account_id: SecureRandom.uuid } }

    assert_response :unprocessable_entity
    assert_equal original_account_id, @recurring_transaction.reload.account_id,
      "a present-but-unresolvable id must not silently detach the account"
  end

  test "create stamps dedup_scope up front so tiers fork and true duplicates collide" do
    post recurring_transactions_url, params: {
      recurring_transaction: { name: "STREAMCO", amount: "5.99", account_id: accounts(:depository).id,
                               first_due_on: (Date.current + 3).iso8601, frequency_preset: "monthly" }
    }
    post recurring_transactions_url, params: {
      recurring_transaction: { name: "STREAMCO", amount: "24.99", account_id: accounts(:depository).id,
                               first_due_on: (Date.current + 9).iso8601, frequency_preset: "monthly" }
    }

    tiers = @family.recurring_transactions.where(name: "STREAMCO").order(:amount)
    assert_equal 2, tiers.count
    assert_equal [ "5.99", "24.99" ], tiers.map(&:dedup_scope)

    # The stamp makes the very first identical duplicate collide on insert.
    post recurring_transactions_url, params: {
      recurring_transaction: { name: "STREAMCO", amount: "5.99", account_id: accounts(:depository).id,
                               first_due_on: (Date.current + 3).iso8601, frequency_preset: "monthly" }
    }
    assert_equal 2, @family.recurring_transactions.where(name: "STREAMCO").count
  end

  test "creating a bill with frequency once schedules that date and no other" do
    due = Date.current + 20

    assert_difference "@family.recurring_transactions.count", 1 do
      post recurring_transactions_url, params: {
        recurring_transaction: {
          name: "Car registration",
          amount: "320",
          account_id: accounts(:depository).id,
          first_due_on: due.iso8601,
          frequency_preset: "once"
        }
      }
    end

    bill = @family.recurring_transactions.find_by!(name: "Car registration")
    assert bill.one_off?
    assert_equal due, bill.anchor_date
    assert_equal due, bill.next_expected_date
    assert_equal [ due ], bill.recurring_occurrences.reload.pluck(:due_on)
    assert_empty bill.schedule.occurrences_between(due + 1, due + 400)

    get edit_recurring_transaction_url(bill), headers: { "Turbo-Frame" => "modal" }
    assert_response :success
    assert_select "option[selected][value=?]", "once"
    assert_select "input[name=?][value=?]", "recurring_transaction[frequency_once_on]", due.iso8601

    get bill_url(bill, display: "history"),
        headers: { "Turbo-Frame" => ActionView::RecordIdentifier.dom_id(bill, :history) }
    assert_response :success
    assert_match I18n.t("bills.detail.once_kind_hint"), response.body
  end

  test "a one-off dated in the past still materializes, and its date can move" do
    due = Date.current - 3

    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "School fee", amount: "80", first_due_on: due.iso8601, frequency_preset: "once"
      }
    }

    bill = @family.recurring_transactions.find_by!(name: "School fee")
    assert_equal [ due ], bill.recurring_occurrences.reload.pluck(:due_on)

    moved = Date.current + 12
    patch recurring_transaction_url(bill), params: {
      recurring_transaction: { frequency_preset: "once", frequency_once_on: moved.iso8601 }
    }

    assert_equal [ moved ], bill.recurring_occurrences.reload.pluck(:due_on)
    assert_equal moved, bill.reload.next_expected_date
  end

  test "switching a repeating bill to once without a date uses its current due date" do
    due = Date.current + 5
    post recurring_transactions_url, params: {
      recurring_transaction: { name: "Tuition", amount: "900", first_due_on: due.iso8601, frequency_preset: "monthly" }
    }
    bill = @family.recurring_transactions.find_by!(name: "Tuition")
    stale = Date.current - 200
    bill.update_columns(anchor_date: stale)

    get edit_recurring_transaction_url(bill), headers: { "Turbo-Frame" => "modal" }
    assert_select "input[name=?][value=?]", "recurring_transaction[frequency_once_on]", due.iso8601

    # What Smart Configure submits: the preset alone, with no date.
    patch recurring_transaction_url(bill), params: { recurring_transaction: { frequency_preset: "once" } }

    assert_equal due, bill.reload.anchor_date
    assert_equal [ due ], bill.recurring_occurrences.reload.pluck(:due_on)
  end

  test "moving a paid one-off is refused and does not add a second occurrence" do
    due = Date.current + 4

    post recurring_transactions_url, params: {
      recurring_transaction: {
        name: "Registration", amount: "80", first_due_on: due.iso8601, frequency_preset: "once"
      }
    }
    bill = @family.recurring_transactions.find_by!(name: "Registration")
    RecurringTransaction::Allocator.new(bill.recurring_occurrences.find_by!(due_on: due)).mark_paid!

    patch recurring_transaction_url(bill), params: {
      recurring_transaction: { frequency_preset: "once", frequency_once_on: (due + 30).iso8601 }
    }

    assert_response :unprocessable_entity
    assert_equal due, bill.reload.anchor_date
    assert_equal [ due ], bill.recurring_occurrences.reload.pluck(:due_on)
  end

  test "marking a bill as an installment plan caps its occurrences and tracks progress" do
    due = Date.current + 5
    post recurring_transactions_url, params: {
      recurring_transaction: { name: "Klarna sofa", amount: "120", first_due_on: due.iso8601, frequency_preset: "monthly" }
    }
    bill = @family.recurring_transactions.find_by!(name: "Klarna sofa")

    patch recurring_transaction_url(bill), params: {
      recurring_transaction: { bill_type: "installment", end_after_count: "4" }
    }

    bill.reload
    assert bill.typed_installment?
    assert bill.ends_after_count?
    assert_equal 4, bill.recurring_occurrences.reload.count, "the plan materializes exactly its four payments"
    assert_equal [ 0, 4 ], bill.installment_progress

    occurrence = bill.recurring_occurrences.order(:due_on).first
    RecurringTransaction::Allocator.new(occurrence).mark_paid!
    assert_equal [ 1, 4 ], bill.reload.installment_progress
  end

  test "update applies a frequency preset as recurrence rules" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { frequency_preset: "biweekly", frequency_weekday: "5" } }

    assert_redirected_to recurring_transactions_url
    rules = @recurring_transaction.reload.recurrence_rules
    assert_equal [ [ "weekly", 2, 5 ] ], rules.map { |rule| [ rule.frequency, rule.interval, rule.weekday ] }
    assert_not_nil @recurring_transaction.anchor_date
  end

  # The bill form moves a due day through the frequency picker, which rewrites
  # the rule and regenerates on save. Two moves in a row (27, 24, 22) must
  # leave the paid October cycle with its one occurrence.
  test "moving a paid bill's due day twice keeps its cycle to one occurrence" do
    travel_to Date.new(2026, 10, 28) do
      sign_in @user
      october = Date.new(2026, 10, 1)..Date.new(2026, 10, 31)

      patch recurring_transaction_url(@recurring_transaction),
            params: { recurring_transaction: { frequency_preset: "monthly", frequency_day_of_month: "27" } }
      paid = @recurring_transaction.recurring_occurrences.find_by!(due_on: Date.new(2026, 10, 27))
      paid.allocations.create!(allocated_amount: 5, currency: "USD", source: "user_created")

      [ 24, 22 ].each do |day|
        patch recurring_transaction_url(@recurring_transaction),
              params: { recurring_transaction: { frequency_preset: "monthly", frequency_day_of_month: day.to_s } }

        assert_redirected_to recurring_transactions_url
        assert_equal [ paid.id ], @recurring_transaction.recurring_occurrences.where(due_on: october).pluck(:id),
                     "moving the due day to the #{day.ordinalize} adds no second October occurrence"
        assert_includes @recurring_transaction.recurring_occurrences.pluck(:due_on), Date.new(2026, 11, day)
      end

      assert_equal 22, @recurring_transaction.reload.expected_day_of_month
      assert_not_includes @recurring_transaction.recurring_occurrences.pluck(:due_on), Date.new(2026, 11, 24)
    end
  end

  test "update with an unchanged frequency does not rewrite the rules" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { frequency_preset: "weekly", frequency_weekday: "3" } }
    original_ids = @recurring_transaction.reload.recurrence_rules.map(&:id)

    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { notes: "edited", frequency_preset: "weekly", frequency_weekday: "3" } }

    assert_equal original_ids, @recurring_transaction.reload.recurrence_rules.map(&:id)
    assert_equal "edited", @recurring_transaction.notes
  end

  test "update with an incomplete frequency re-renders the form" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { frequency_preset: "weekly" } },
          headers: { "Turbo-Frame" => "modal" }

    assert_response :unprocessable_entity
    assert_empty @recurring_transaction.reload.recurrence_rules
  end

  test "update applies a custom interval as one rule every N units" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: {
            frequency_preset: "interval", frequency_interval: "3", frequency_interval_unit: "weekly", frequency_weekday: "5"
          } }

    assert_redirected_to recurring_transactions_url
    rule = @recurring_transaction.reload.recurrence_rules.sole
    assert_equal [ "weekly", 3, 5 ], [ rule.frequency, rule.interval, rule.weekday ]
    assert @recurring_transaction.schedule_pinned?
  end

  test "update with an out-of-range interval re-renders without touching the rules" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: {
            frequency_preset: "interval", frequency_interval: "0", frequency_interval_unit: "monthly"
          } },
          headers: { "Turbo-Frame" => "modal" }

    assert_response :unprocessable_entity
    assert_empty @recurring_transaction.reload.recurrence_rules
  end

  test "edit pre-fills a custom interval" do
    @recurring_transaction.update!(anchor_date: Date.current)
    @recurring_transaction.recurrence_rules.create!(frequency: "monthly", interval: 2, day_of_month: 12)

    get edit_recurring_transaction_url(@recurring_transaction)

    assert_response :success
    assert_select "select[name='recurring_transaction[frequency_preset]'] option[selected][value='interval']"
    assert_select "input[name='recurring_transaction[frequency_interval]'][value='2']"
    assert_select "select[name='recurring_transaction[frequency_interval_unit]'] option[selected][value='monthly']"
  end

  test "update rejects a non-http scheme instead of storing it" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { payment_url: "javascript:alert(1)" } }

    assert_response :unprocessable_entity
    assert_nil @recurring_transaction.reload.payment_url
  end

  test "update saves autopay and notes" do
    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { autopay: "1", notes: "Account 4821" } }

    @recurring_transaction.reload
    assert @recurring_transaction.autopay?
    assert_equal "Account 4821", @recurring_transaction.notes
  end

  test "update can turn autopay back off" do
    @recurring_transaction.update!(autopay: true)

    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { autopay: "0" } }

    assert_not @recurring_transaction.reload.autopay?
  end

  test "update clears the payment link when submitted blank" do
    @recurring_transaction.update!(payment_url: "https://pay.example.com")

    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { payment_url: "" } }

    assert_nil @recurring_transaction.reload.payment_url
  end

  # One biller routinely owns several bills that all pay at one portal, so the link
  # can be fanned out on request. It must never reach a row outside the family.
  test "update copies the payment link to sibling bills of the same merchant when asked" do
    sibling = @family.recurring_transactions.create!(
      account: accounts(:depository),
      merchant: @recurring_transaction.merchant,
      amount: 4.99,
      dedup_scope: "4.99",
      currency: "USD",
      expected_day_of_month: 20,
      last_occurrence_date: Date.current,
      next_expected_date: 1.month.from_now.to_date,
      status: "active"
    )
    other_merchant_bill = @family.recurring_transactions.create!(
      account: accounts(:depository),
      merchant: merchants(:amazon),
      amount: 7.99,
      currency: "USD",
      expected_day_of_month: 21,
      last_occurrence_date: Date.current,
      next_expected_date: 1.month.from_now.to_date,
      status: "active"
    )

    patch recurring_transaction_url(@recurring_transaction),
          params: {
            recurring_transaction: { payment_url: "https://pay.example.com" },
            apply_to_siblings: "1"
          }

    assert_equal "https://pay.example.com", sibling.reload.payment_url
    assert_nil other_merchant_bill.reload.payment_url
  end

  # Auto-detection leaves merchant_id null whenever the provider feed gave it nothing
  # to match on, so most real bills are identified by name alone. Matching siblings on
  # merchant only would skip them entirely.
  test "update copies the payment link to name-matched siblings when there is no merchant" do
    named = @family.recurring_transactions.create!(
      account: accounts(:depository),
      name: "TWITCH",
      amount: 24.99,
      currency: "USD",
      expected_day_of_month: 21,
      last_occurrence_date: Date.current,
      next_expected_date: 1.month.from_now.to_date,
      status: "active"
    )
    same_name = @family.recurring_transactions.create!(
      account: accounts(:depository),
      name: "TWITCH",
      amount: 5.99,
      dedup_scope: "5.99",
      currency: "USD",
      expected_day_of_month: 8,
      last_occurrence_date: Date.current,
      next_expected_date: 1.month.from_now.to_date,
      status: "active"
    )
    different_name = @family.recurring_transactions.create!(
      account: accounts(:depository),
      name: "HUNTR.CO",
      amount: 40,
      currency: "USD",
      expected_day_of_month: 28,
      last_occurrence_date: Date.current,
      next_expected_date: 1.month.from_now.to_date,
      status: "active"
    )

    patch recurring_transaction_url(named),
          params: {
            recurring_transaction: { payment_url: "https://twitch.tv/subscriptions" },
            apply_to_siblings: "1"
          }

    assert_equal "https://twitch.tv/subscriptions", same_name.reload.payment_url
    assert_nil different_name.reload.payment_url
    # A merchant-backed row must not be swept up by a name match.
    assert_nil @recurring_transaction.reload.payment_url
  end

  test "update does not touch siblings unless asked" do
    sibling = @family.recurring_transactions.create!(
      account: accounts(:depository),
      merchant: @recurring_transaction.merchant,
      amount: 4.99,
      dedup_scope: "4.99",
      currency: "USD",
      expected_day_of_month: 20,
      last_occurrence_date: Date.current,
      next_expected_date: 1.month.from_now.to_date,
      status: "active"
    )

    patch recurring_transaction_url(@recurring_transaction),
          params: { recurring_transaction: { payment_url: "https://pay.example.com" } }

    assert_nil sibling.reload.payment_url
  end

  test "update cannot reach another family's recurring transaction" do
    other_family_recurring = families(:empty).recurring_transactions.create!(
      name: "Someone else's bill",
      amount: 10,
      currency: "USD",
      expected_day_of_month: 3,
      last_occurrence_date: Date.current,
      next_expected_date: 1.month.from_now.to_date,
      status: "active"
    )

    patch recurring_transaction_url(other_family_recurring),
          params: { recurring_transaction: { payment_url: "https://evil.example.com" } }

    assert_response :not_found
    assert_nil other_family_recurring.reload.payment_url
  end

  # A bill outliving its own price is the normal case. These used to be
  # create-only, so the only way to record a rise was delete-and-recreate,
  # which takes the occurrences and allocations with it.
  test "the edit dialog exposes name, amount and account" do
    series = recurring_transactions(:netflix_subscription)
    get edit_recurring_transaction_url(series)
    assert_response :success

    fields = response.body.scan(/name="recurring_transaction\[([a-z_]+)\]"/).flatten.uniq
    %w[name amount account_id].each do |field|
      assert_includes fields, field, "#{field} should be editable after creation"
    end
    refute_includes fields, "first_due_on",
      "first_due_on is inert on a persisted series; the frequency picker owns the schedule"
  end

  test "updating name, amount and account persists all three" do
    series = recurring_transactions(:netflix_subscription)
    other  = accounts(:credit_card)

    patch recurring_transaction_url(series), params: {
      recurring_transaction: { name: "Netflix Premium", amount: 24.99, account_id: other.id }
    }
    series.reload

    assert_equal "Netflix Premium", series.name
    assert_equal 24.99, series.amount.to_f
    assert_equal other.id, series.account_id
  end
  test "a bill cannot be pointed at an account the user cannot reach" do
    series = recurring_transactions(:netflix_subscription)
    foreign = families(:empty).accounts.create!(
      name: "Someone else's checking", balance: 0, currency: "USD",
      accountable: Depository.new
    )
    refute_equal series.family_id, foreign.family_id

    patch recurring_transaction_url(series), params: {
      recurring_transaction: { account_id: foreign.id }
    }

    refute_equal foreign.id, series.reload.account_id,
      "a crafted account_id must not reach another family's account"
  end

  test "editing an income series keeps its negative sign" do
    income = recurring_transactions(:netflix_subscription)
    income.update!(bill_type: "income", amount: -2000)

    patch recurring_transaction_url(income), params: {
      recurring_transaction: { amount: 2500 }
    }

    assert_equal(-2500, income.reload.amount.to_f,
      "income is stored negative; a raw assignment would flip it into a bill")
  end

  test "the edit form shows an income amount as a positive magnitude" do
    income = recurring_transactions(:netflix_subscription)
    income.update!(bill_type: "income", amount: -2000)

    get edit_recurring_transaction_url(income)

    assert_response :success
    # The stored sign is bookkeeping; the form edits what the paycheck pays.
    assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "2000.00"
  end

  test "the edit form shows a bill amount as it is stored" do
    get edit_recurring_transaction_url(recurring_transactions(:netflix_subscription))

    assert_response :success
    assert_select "input[name=?][value=?]", "recurring_transaction[amount]", "15.99"
  end
  # Detected bills carry a merchant and no name of their own. The field has to
  # arrive seeded, or it renders empty and, being required, browsers refuse to
  # submit the whole form; and the rename has to actually show, or it is a
  # control that silently does nothing.
  test "renaming a detected bill seeds the field and takes effect" do
    series = recurring_transactions(:netflix_subscription)
    assert series.name.blank?, "premise: this bill is named by its merchant"
    assert series.merchant.present?

    get edit_recurring_transaction_url(series)
    assert_select "input[name=?][value=?]", "recurring_transaction[name]", series.display_name

    patch recurring_transaction_url(series), params: {
      recurring_transaction: { name: "Netflix Premium" }
    }

    assert_equal "Netflix Premium", series.reload.display_name,
      "a name the user typed should win over the detected merchant"
  end

  # --- Suggested-series review: confirm/dismiss from either page ---

  test "confirming from the Bills page returns there and reconstructs the bill's history" do
    last_month_ninth = Date.current.beginning_of_month + 8.days - 1.month
    suggestion = @family.recurring_transactions.create!(
      name: "CITY WATER", account: accounts(:depository), amount: 80, currency: "USD",
      expected_day_of_month: 9, last_occurrence_date: last_month_ninth,
      next_expected_date: last_month_ninth + 1.month, status: "suggested", manual: false
    )
    accounts(:depository).entries.create!(
      date: last_month_ninth, amount: 80, currency: "USD", name: "CITY WATER",
      entryable: Transaction.new
    )

    post confirm_recurring_transaction_url(suggestion), headers: { "HTTP_REFERER" => bills_url }

    assert_redirected_to bills_url
    assert suggestion.reload.active?
    assert_operator suggestion.recurring_occurrences.count, :>, 0,
      "confirming must materialize the schedule"
    assert suggestion.recurring_occurrences.paid.where(due_on: last_month_ninth).exists?,
      "confirming must close history a real entry anchors"
  end

  test "confirming while a pipeline holds the family lock queues the history instead of dropping it" do
    paid_on, suggestion, entry = suggested_bill_with_past_payment

    with_family_lock_held_elsewhere(@family.id) do
      assert_enqueued_with(job: BackfillRecurringHistoryJob, args: [ suggestion.id ]) do
        post confirm_recurring_transaction_url(suggestion)
      end
    end

    assert suggestion.reload.active?
    assert_equal 0, suggestion.recurring_occurrences.paid.where(due_on: paid_on).count,
      "nothing may run under another session's lock"

    perform_enqueued_jobs(only: BackfillRecurringHistoryJob)

    assert_equal 1, suggestion.recurring_occurrences.paid.where(due_on: paid_on).count
    assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?
  end

  # The backfill prunes unpaid past rows of whatever it is scoped to, so it
  # must stay scoped to the bill being confirmed.
  test "confirming a detected bill leaves other bills' past rows alone" do
    _, suggestion, = suggested_bill_with_past_payment
    other_row = @recurring_transaction.recurring_occurrences.create!(
      family: @family, original_due_on: 3.months.ago.to_date, due_on: 3.months.ago.to_date, currency: "USD"
    )

    post confirm_recurring_transaction_url(suggestion)

    assert suggestion.reload.active?
    assert RecurringOccurrence.exists?(other_row.id), "another bill's history is not this confirm's to prune"
  end

  test "confirming an already-active bill queues nothing" do
    assert @recurring_transaction.active?

    assert_no_enqueued_jobs(only: BackfillRecurringHistoryJob) do
      with_family_lock_held_elsewhere(@family.id) { post confirm_recurring_transaction_url(@recurring_transaction) }
    end
  end

  # toggle_status reaches a detected bill too: the action only asks whether the
  # series is active, and a suggestion is not.
  test "toggling a detected bill on links its past payments" do
    paid_on, suggestion, entry = suggested_bill_with_past_payment

    assert_difference -> { suggestion.recurring_occurrences.paid.where(due_on: paid_on).count }, 1 do
      post toggle_status_recurring_transaction_url(suggestion)
    end
    assert suggestion.reload.active?
    assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?
  end

  # The status change has committed by the time the reconstruction runs, so a
  # failure in it must not turn the user's own action into an error: it is
  # reported and handed to the job, which retries.
  test "toggling a detected bill on succeeds when reconstructing its history fails" do
    _, suggestion, = suggested_bill_with_past_payment
    RecurringTransaction::HistoryBackfiller.any_instance.stubs(:run!).raises(ActiveRecord::Deadlocked)
    Rails.error.expects(:report).with(instance_of(ActiveRecord::Deadlocked), has_entry(handled: true))

    assert_enqueued_with(job: BackfillRecurringHistoryJob, args: [ suggestion.id ]) do
      post toggle_status_recurring_transaction_url(suggestion)
    end

    assert_redirected_to recurring_transactions_url
    assert suggestion.reload.active?
  end

  # Activation changes status, a schedule-shaping column, so regeneration runs
  # in the same after_commit chain. A raise there stops the callbacks after
  # it, so the history reconstruction must not sit behind it.
  test "toggling a detected bill on still links its past payments when regenerating its future fails" do
    paid_on, suggestion, entry = suggested_bill_with_past_payment
    RecurringTransaction::OccurrenceGenerator.any_instance.stubs(:regenerate_future!).raises(RuntimeError, "regeneration failed")

    assert_raises(RuntimeError) { post toggle_status_recurring_transaction_url(suggestion) }

    assert suggestion.reload.active?
    assert_equal 1, suggestion.recurring_occurrences.paid.where(due_on: paid_on).count
    assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?
  end

  # The history pass matches against every open occurrence, so the upcoming
  # one must exist by then: a payment made a couple of days early belongs to
  # it, not to the unpaid cycle before.
  test "toggling a detected bill on links an early payment to the upcoming occurrence" do
    travel_to Date.new(2026, 10, 14) do
      suggestion = @family.recurring_transactions.create!(
        name: "CITY POWER", account: accounts(:depository), amount: 95, currency: "USD",
        expected_day_of_month: 16, last_occurrence_date: Date.new(2026, 9, 16),
        next_expected_date: Date.new(2026, 10, 16), status: "suggested", manual: false
      )
      entry = accounts(:depository).entries.create!(
        date: Date.new(2026, 10, 14), amount: 95, currency: "USD", name: "CITY POWER",
        entryable: Transaction.new
      )

      post toggle_status_recurring_transaction_url(suggestion)

      upcoming = suggestion.recurring_occurrences.find_by!(due_on: Date.new(2026, 10, 16))
      assert RecurringAllocation.where(recurring_occurrence: upcoming, entry_id: entry.id).exists?,
        "the early payment belongs to the occurrence it was paid ahead of"
    end
  end

  test "resuming a paused bill does not reconstruct its history" do
    paid_on, suggestion, = suggested_bill_with_past_payment
    suggestion.update_columns(status: "inactive")

    assert_no_difference -> { suggestion.recurring_occurrences.where(due_on: paid_on).count } do
      post toggle_status_recurring_transaction_url(suggestion)
    end
    assert suggestion.reload.active?
  end

  test "confirming twice does not double anything" do
    suggestion = @family.recurring_transactions.create!(
      name: "CITY GAS", account: accounts(:depository), amount: 55, currency: "USD",
      expected_day_of_month: 9,
      last_occurrence_date: Date.current.beginning_of_month + 8.days - 1.month,
      next_expected_date: Date.current.beginning_of_month + 8.days,
      status: "suggested", manual: false
    )

    post confirm_recurring_transaction_url(suggestion)
    state = suggestion.recurring_occurrences.order(:due_on).pluck(:due_on, :status)

    post confirm_recurring_transaction_url(suggestion)

    assert_equal state, suggestion.recurring_occurrences.order(:due_on).pluck(:due_on, :status)
  end

  test "dismissing from the Bills page tombstones and returns there" do
    suggestion = @family.recurring_transactions.create!(
      name: "PHANTOM SUB", account: accounts(:depository), amount: 12, currency: "USD",
      expected_day_of_month: 5, last_occurrence_date: 1.month.ago.to_date,
      next_expected_date: Date.current, status: "suggested", manual: false
    )

    post dismiss_recurring_transaction_url(suggestion), headers: { "HTTP_REFERER" => bills_url }

    assert_redirected_to bills_url
    assert suggestion.reload.ended?
  end

  test "settings reviews detected income in its own strip, not as a possible bill" do
    create_series(name: "CITY WATER", amount: 80, status: "suggested")
    create_series(name: "ACME PAYROLL", amount: -2500, bill_type: "income", status: "suggested")

    get recurring_transactions_url

    assert_response :success
    assert_select "[data-persisted-disclosure-key-value='bills-suggested']", text: /CITY WATER/ do |strip|
      assert_no_match "ACME PAYROLL", strip.text
    end
    assert_select "[data-persisted-disclosure-key-value='income-suggested']", text: /ACME PAYROLL/ do
      assert_select "a", text: I18n.t("recurring_transactions.suggested_income.dismiss")
    end
  end

  test "confirming an income suggestion says income was added" do
    suggestion = create_series(name: "ACME PAYROLL", amount: -2500, bill_type: "income", status: "suggested")

    post confirm_recurring_transaction_url(suggestion)

    assert_equal I18n.t("recurring_transactions.confirmed_income"), flash[:notice]
  end

  # --- "Search all your transactions" picker inside the add dialog ---

  test "the add dialog links to the picker whether or not detection found anything" do
    get new_recurring_transaction_url, headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.search_all_cta"), response.body
    assert_select "a[href=?]", new_recurring_transaction_path(picker: 1)
  end

  test "picker lists recent outflows as prefill links" do
    entry = picker_entry(name: "ACME POWER", amount: 120)

    get new_recurring_transaction_url(picker: 1), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match "ACME POWER", response.body
    assert_select "a[href=?]", new_recurring_transaction_path(entry_id: entry.id)
  end

  test "picker filters by sign in each mode" do
    picker_entry(name: "PAYCHECK DEPOSIT", amount: -900)
    picker_entry(name: "ACME POWER", amount: 120)

    get new_recurring_transaction_url(picker: 1), headers: { "Turbo-Frame" => "modal" }
    assert_match "ACME POWER", response.body
    assert_no_match "PAYCHECK DEPOSIT", response.body

    get new_recurring_transaction_url(picker: 1, income: 1), headers: { "Turbo-Frame" => "modal" }
    assert_match "PAYCHECK DEPOSIT", response.body
    assert_no_match "ACME POWER", response.body
  end

  test "picker search matches the merchant behind a bank-blob entry name" do
    picker_entry(name: "ACH WEB PMT 0042", amount: 15.49, merchant: merchants(:netflix))
    picker_entry(name: "UNRELATED CHARGE", amount: 8)

    get new_recurring_transaction_url(picker: 1, q: merchants(:netflix).name),
        headers: { "Turbo-Frame" => "modal" }

    assert_match "ACH WEB PMT 0042", response.body
    assert_no_match "UNRELATED CHARGE", response.body
  end

  test "picker search matches notes" do
    picker_entry(name: "CHECK 1042", amount: 300, notes: "quarterly water bill")
    picker_entry(name: "CHECK 1043", amount: 300)

    get new_recurring_transaction_url(picker: 1, q: "quarterly water"),
        headers: { "Turbo-Frame" => "modal" }

    assert_match "CHECK 1042", response.body
    assert_no_match "CHECK 1043", response.body
  end

  test "picker search treats LIKE metacharacters as literals" do
    picker_entry(name: "100% Juice Co", amount: 6)
    picker_entry(name: "1003 Deli", amount: 9)

    get new_recurring_transaction_url(picker: 1, q: "100%"), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match "100% Juice Co", response.body
    assert_no_match "1003 Deli", response.body
  end

  test "picker hides transfers and excluded entries" do
    picker_entry(name: "CARD PAYMENT", amount: 200, kind: "cc_payment")
    picker_entry(name: "HIDDEN CHARGE", amount: 25, excluded: true)
    picker_entry(name: "REAL CHARGE", amount: 25)

    get new_recurring_transaction_url(picker: 1), headers: { "Turbo-Frame" => "modal" }

    assert_match "REAL CHARGE", response.body
    assert_no_match "CARD PAYMENT", response.body
    assert_no_match "HIDDEN CHARGE", response.body
  end

  test "picker never shows an account the member was not given, even on exact match" do
    hidden = picker_entry(name: "PRIVATE BROKERAGE FEE", amount: 30, account: accounts(:investment))
    member = users(:family_member)
    member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))
    sign_in member

    get new_recurring_transaction_url(picker: 1, q: "PRIVATE BROKERAGE FEE"),
        headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    # The no-results copy echoes the query, so assert on the row link itself.
    assert_select "a[href=?]", new_recurring_transaction_path(entry_id: hidden.id), count: 0
    assert_match I18n.t("recurring_transactions.pick_entry.back"), response.body
  end

  test "an entry already backing a bill carries a chip instead of being hidden" do
    claimed = picker_entry(name: "NETFLIX.COM", amount: 15.99)
    series = @family.recurring_transactions.create!(
      name: "Netflix", account: accounts(:depository), amount: 15.99, currency: "USD",
      dedup_scope: "chip", expected_day_of_month: Date.current.day,
      last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,
      status: "active", manual: true
    )
    occurrence = series.recurring_occurrences.order(:due_on).first
    occurrence.allocations.create!(
      entry: claimed, allocated_amount: 15.99, currency: "USD", source: "user_created"
    )
    picker_entry(name: "UNCLAIMED CHARGE", amount: 12)

    get new_recurring_transaction_url(picker: 1), headers: { "Turbo-Frame" => "modal" }

    assert_match I18n.t("recurring_transactions.picker_row.claimed", name: "Netflix"), response.body
    # The chip names its bill once, on the claimed row only.
    assert_equal 1, response.body.scan(
      I18n.t("recurring_transactions.picker_row.claimed", name: "Netflix")
    ).size
  end

  test "picker caps at twenty rows and says so" do
    25.times { |i| picker_entry(name: "CHARGE #{format('%02d', i)}", amount: 5 + i) }

    get new_recurring_transaction_url(picker: 1), headers: { "Turbo-Frame" => "modal" }

    assert_equal RecurringTransactionsController::PICKER_SHOWN,
      response.body.scan(/CHARGE \d\d/).uniq.size
    assert_match I18n.t("recurring_transactions.pick_entry.showing_recent",
      count: RecurringTransactionsController::PICKER_SHOWN), response.body
  end

  test "picker with no results explains and offers the way back" do
    get new_recurring_transaction_url(picker: 1, q: "zzz-nothing-matches"),
        headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match CGI.escapeHTML("zzz-nothing-matches"), response.body
    assert_match I18n.t("recurring_transactions.pick_entry.back"), response.body
  end

  # The declare, edit and suggestion paths shipped with Bills, so they honor
  # the same preview gate as every other Bills surface. Direct URLs included:
  # the gate is a before_action, not a matter of which buttons render.
  test "the bills-era actions sit behind the preview gate" do
    @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))

    get new_recurring_transaction_url
    assert_redirected_to root_path

    assert_no_difference "RecurringTransaction.count" do
      post recurring_transactions_url, params: { recurring_transaction: {
        name: "Gated", amount: 10, first_due_on: Date.current.iso8601, frequency_preset: "monthly"
      } }
    end
    assert_redirected_to root_path

    assert_no_changes -> { @recurring_transaction.reload.name } do
      patch recurring_transaction_url(@recurring_transaction), params: { recurring_transaction: { name: "Renamed" } }
    end
    assert_redirected_to root_path

    suggestion = create_series(name: "Maybe A Bill", status: "suggested")
    post confirm_recurring_transaction_url(suggestion)
    assert_redirected_to root_path
    assert suggestion.reload.suggested?
  end

  # The suggestion strip is shared with the Bills overview, whose section
  # recipe it now follows.
  test "settings list the suggestions under the overview's heading, collapsible" do
    create_series(name: "Maybe A Bill", status: "suggested")

    get recurring_transactions_url
    assert_response :success

    assert_select ".bg-surface-inset > details[data-persisted-disclosure-key-value='bills-suggested']" do
      assert_select "summary div.uppercase", text: /#{I18n.t("recurring_transactions.suggested.title")}\s*·\s*1/
      assert_select ".bg-container.rounded-lg", text: /Maybe A Bill/
      assert_select "a", text: I18n.t("recurring_transactions.suggested.confirm")
    end
  end

  test "the pre-bills settings actions stay reachable without the preview flag" do
    @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))

    get recurring_transactions_url
    assert_response :success

    post toggle_status_recurring_transaction_url(@recurring_transaction)
    assert_redirected_to recurring_transactions_url
  end

  # Sharing is per account: a read-only share may SEE the series everywhere the
  # app lists it, and must not be able to change or remove it. Mirrors
  # RecurringOccurrencesController#ensure_series_writable.
  test "a read-only account share can see but not mutate a series" do
    member = users(:family_member)
    member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))
    # The credit card fixture is shared with the member read_only.
    series = create_series(name: "Shared Read Only", account: accounts(:credit_card))
    suggestion = create_series(name: "Shared Suggestion", account: accounts(:credit_card), status: "suggested")

    sign_in member

    # Visible: the read dialog opens. The write guard bites only on mutation.
    get edit_recurring_transaction_url(series), headers: { "Turbo-Frame" => "modal" }
    assert_response :success
    assert_match "Shared Read Only", response.body

    patch recurring_transaction_url(series), params: { recurring_transaction: { name: "Hijacked" } }
    assert_response :not_found
    assert_equal "Shared Read Only", series.reload.name

    post toggle_status_recurring_transaction_url(series)
    assert_response :not_found
    assert series.reload.active?

    post confirm_recurring_transaction_url(suggestion)
    assert_response :not_found
    assert suggestion.reload.suggested?

    post dismiss_recurring_transaction_url(suggestion)
    assert_response :not_found
    assert suggestion.reload.suggested?

    delete recurring_transaction_url(series)
    assert_response :not_found
    assert series.reload.persisted?
  end

  test "an accountless series carries no account write gate" do
    series = create_series(name: "No Account", account: nil)

    patch recurring_transaction_url(series), params: { recurring_transaction: { name: "Renamed Fine" } }

    assert_response :redirect
    assert_equal "Renamed Fine", series.reload.name
  end

  # The destination is a write too: attaching a series to an account changes
  # what that account's owners see, so a read-only share cannot receive one,
  # whether by edit or at declaration.
  test "a read-only account cannot become a series' destination" do
    member = users(:family_member)
    member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))
    series = create_series(name: "Wandering Bill", account: nil)

    sign_in member

    patch recurring_transaction_url(series), params: { recurring_transaction: { account_id: accounts(:credit_card).id } }
    assert_response :unprocessable_entity
    assert_nil series.reload.account_id

    assert_no_difference "RecurringTransaction.count" do
      post recurring_transactions_url, params: { recurring_transaction: {
        name: "Declared On Read Only", amount: 12, first_due_on: Date.current.iso8601,
        frequency_preset: "monthly", account_id: accounts(:credit_card).id
      } }
    end
    assert_response :unprocessable_entity
    assert_match I18n.t("recurring_transactions.create.account_invalid"), response.body
  end

  # Clearing a payment link is a statement about one bill; the opt-in copy
  # must not blank the siblings' own links on the way through.
  test "clearing the payment link never blanks the siblings" do
    source = create_series(name: "Twitch Tier 1", merchant: merchants(:netflix), payment_url: "https://pay.example/1")
    sibling = create_series(name: "Twitch Tier 2", merchant: merchants(:netflix), payment_url: "https://pay.example/keep")

    patch recurring_transaction_url(source), params: {
      apply_to_siblings: "1",
      recurring_transaction: { payment_url: "" }
    }

    assert_response :redirect
    assert_nil source.reload.payment_url.presence
    assert_equal "https://pay.example/keep", sibling.reload.payment_url
  end

  test "the sibling copy skips series on accounts the user cannot write" do
    member = users(:family_member)
    member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))

    source = create_series(name: "Portal Bill", account: nil, merchant: merchants(:netflix))
    # The credit card fixture is shared with the member read_only: visible,
    # therefore inside accessible_by, and exactly what the copy must skip.
    read_only_sibling = create_series(name: "Portal Bill RO", account: accounts(:credit_card),
                                      merchant: merchants(:netflix), payment_url: "https://pay.example/theirs")

    sign_in member
    patch recurring_transaction_url(source), params: {
      apply_to_siblings: "1",
      recurring_transaction: { payment_url: "https://pay.example/mine" }
    }

    assert_response :redirect
    assert_equal "https://pay.example/mine", source.reload.payment_url
    assert_equal "https://pay.example/theirs", read_only_sibling.reload.payment_url
  end

  # "Create bill" from a transaction used to save a second bill for a payment
  # that was already paying one (#4368): the declared bill is keyed by name,
  # the detected one by merchant, so no unique index could ever collide.
  test "new from a transaction a bill already covers names that bill and links to it" do
    entry, detected = covered_entry_and_detected_bill

    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.covered_title"), response.body
    assert_select "a[href=?]", bill_path(detected), text: I18n.t("recurring_transactions.new.covered_open")
    assert_select "input[type=hidden][name=entry_id][value=?]", entry.id
    assert_select "input[type=hidden][name=allow_duplicate][value=1]"
    assert_select "a[href=?]", confirm_recurring_transaction_path(detected), count: 0
  end

  # An inflow is covered by a recurring income, not a bill, and the dialog
  # around it is already the income one, so the warning speaks of income too.
  test "new from a deposit a recurring income covers speaks of income" do
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: -1840, currency: "USD", name: "ACME PAYROLL",
      entryable: Transaction.new(merchant: covering_merchant)
    )
    income = @family.recurring_transactions.create!(
      account: accounts(:depository), merchant: covering_merchant, name: nil, bill_type: "income",
      amount: -1840, currency: "USD", expected_day_of_month: Date.current.day,
      last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,
      status: "active", manual: false, occurrence_count: 2
    )

    { "active" => %w[covered_income_title covered_title], "suggested" => %w[covered_income_suggested_title covered_suggested_title] }.each do |status, (income_title, bill_title)|
      income.update!(status: status)

      get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

      assert_response :success
      assert_match I18n.t("recurring_transactions.new.#{income_title}"), response.body
      assert_no_match I18n.t("recurring_transactions.new.#{bill_title}"), response.body
      assert_select "a[href=?]", bill_path(income), text: I18n.t("recurring_transactions.new.covered_income_open")
      assert_match I18n.t("recurring_transactions.new.covered_income_create_anyway"), response.body
    end
    assert_select "a[href=?]", confirm_recurring_transaction_path(income), text: I18n.t("recurring_transactions.new.covered_income_confirm")
  end

  # A suggestion is a bill Sure found and is waiting on. Saving a separate one
  # now would only become a duplicate when the suggestion is confirmed, so the
  # dialog offers the confirm instead, with the separate bill still behind it.
  test "new from a transaction a suggested bill covers offers to confirm it" do
    entry, suggested = covered_entry_and_detected_bill(status: "suggested")

    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.covered_suggested_title"), response.body
    assert_no_match I18n.t("recurring_transactions.new.covered_title"), response.body
    # Confirming links payments within the bill's tolerance, not necessarily
    # this one: covering accepts 0.5x to 2x. The copy must not promise it.
    assert_select "p", text: I18n.t("recurring_transactions.new.covered_suggested_body", name: suggested.display_name)
    assert_no_match "track this payment", response.body
    assert_select "a[href=?][data-turbo-method=post][data-turbo-frame=_top]",
                  confirm_recurring_transaction_path(suggested),
                  text: I18n.t("recurring_transactions.new.covered_confirm")
    assert_select "a[href=?]", bill_path(suggested), text: I18n.t("recurring_transactions.new.covered_open")
    assert_select "input[type=hidden][name=allow_duplicate][value=1]"
  end

  # The confirm action 404s for a read-only share, so the dialog must not
  # offer a button that can only fail.
  test "a read-only share is told about the suggestion but not offered the confirm" do
    member = users(:family_member)
    member.update!(preferences: (member.preferences || {}).merge("preview_features_enabled" => true))
    # The credit card fixture is shared with the member read_only.
    entry, suggested = covered_entry_and_detected_bill(status: "suggested", account: accounts(:credit_card))

    sign_in member
    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_match I18n.t("recurring_transactions.new.covered_suggested_title"), response.body
    assert_select "a[href=?]", confirm_recurring_transaction_path(suggested), count: 0
    assert_select "a[href=?]", bill_path(suggested)
  end

  test "new from a transaction no bill covers shows no warning" do
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",
      entryable: Transaction.new(merchant: covering_merchant)
    )

    get new_recurring_transaction_url(entry_id: entry.id), headers: { "Turbo-Frame" => "modal" }

    assert_response :success
    assert_no_match I18n.t("recurring_transactions.new.covered_title"), response.body
    assert_select "input[type=hidden][name=entry_id][value=?]", entry.id
    assert_select "input[name=allow_duplicate]", count: 0
  end

  # The submitted fields carry only a name; the detected bill has a merchant
  # and no name. Identity has to come from the posted entry, or this passes.
  test "create refuses a second bill for a transaction a merchant-keyed bill covers" do
    entry, detected = covered_entry_and_detected_bill

    assert_no_difference "RecurringTransaction.count" do
      post recurring_transactions_url, params: covered_create_params(entry)
    end

    assert_response :unprocessable_entity
    assert_match I18n.t("recurring_transactions.new.covered_title"), response.body
    assert_select "a[href=?]", bill_path(detected)
  end

  test "create makes the separate bill when asked to" do
    entry, = covered_entry_and_detected_bill

    assert_difference "RecurringTransaction.count", 1 do
      post recurring_transactions_url, params: covered_create_params(entry).merge(allow_duplicate: "1")
    end

    assert_redirected_to bills_path
  end

  # The dialog only ever posts "1". Anything else, such as the "0" or "false"
  # a direct POST might send, is not the separate-bill choice.
  test "create refuses a covered transaction when allow_duplicate is anything but 1" do
    entry, = covered_entry_and_detected_bill

    [ "0", "false" ].each do |value|
      assert_no_difference "RecurringTransaction.count", "allow_duplicate=#{value} skipped the check" do
        post recurring_transactions_url, params: covered_create_params(entry).merge(allow_duplicate: value)
      end

      assert_response :unprocessable_entity
      assert_match I18n.t("recurring_transactions.new.covered_title"), response.body
    end
  end

  test "a failed create does not turn another allow_duplicate value into the choice" do
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",
      entryable: Transaction.new(merchant: covering_merchant)
    )
    params = covered_create_params(entry).merge(allow_duplicate: "0")
    params[:recurring_transaction][:first_due_on] = ""

    post recurring_transactions_url, params: params

    assert_response :unprocessable_entity
    assert_select "input[type=hidden][name=entry_id][value=?]", entry.id
    assert_select "input[name=allow_duplicate]", count: 0
  end

  test "create from a transaction no bill covers still saves" do
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",
      entryable: Transaction.new(merchant: covering_merchant)
    )

    assert_difference "RecurringTransaction.count", 1 do
      post recurring_transactions_url, params: covered_create_params(entry)
    end

    assert_redirected_to bills_path
  end

  # "Create a separate bill anyway" is a choice the user already made. A
  # validation error on that submission must not drop it, or fixing the error
  # and resubmitting is refused again behind the warning.
  test "a failed create keeps the separate-bill choice on the re-render" do
    entry, = covered_entry_and_detected_bill
    params = covered_create_params(entry).merge(allow_duplicate: "1")
    params[:recurring_transaction][:first_due_on] = ""

    assert_no_difference "RecurringTransaction.count" do
      post recurring_transactions_url, params: params
    end

    assert_response :unprocessable_entity
    assert_match ERB::Util.html_escape(I18n.t("recurring_transactions.create.due_date_required")), response.body
    assert_select "input[type=hidden][name=entry_id][value=?]", entry.id
    assert_select "input[type=hidden][name=allow_duplicate][value=1]"
  end

  test "a failed create that never chose a separate bill does not gain the choice" do
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",
      entryable: Transaction.new(merchant: covering_merchant)
    )
    params = covered_create_params(entry)
    params[:recurring_transaction][:first_due_on] = ""

    post recurring_transactions_url, params: params

    assert_response :unprocessable_entity
    assert_select "input[type=hidden][name=entry_id][value=?]", entry.id
    assert_select "input[name=allow_duplicate]", count: 0
  end

  # Two submissions from the same transaction could both see no covering bill
  # and both save, and so could a submission racing an allocation of that
  # transaction or a "Mark as recurring" on it. The check and the save hold
  # the entry lock the Allocator takes, so each waits for the other.
  test "create checks for a covering bill and saves while holding the entry lock" do
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",
      entryable: Transaction.new(merchant: covering_merchant)
    )
    connection = ActiveRecord::Base.connection
    outside = connection.open_transactions
    seen = {}

    RecurringTransactionsController.any_instance.stubs(:covering_series_for)
      .with { seen[:check] = [ connection.open_transactions, entry_lock_held?(entry) ]; true }.returns(nil)
    RecurringTransaction::DeclaredBill.stubs(:save)
      .with { seen[:save] = [ connection.open_transactions, entry_lock_held?(entry) ]; true }.returns(true)
    assert_not entry_lock_held?(entry), "precondition: nothing holds the entry lock before the request"

    post recurring_transactions_url, params: covered_create_params(entry)

    assert_redirected_to bills_path
    assert_operator seen[:check].first, :>, outside, "the covering check ran outside a transaction"
    assert_operator seen[:save].first, :>, outside, "the save ran outside a transaction"
    assert seen[:check].last, "the covering check ran without the entry lock"
    assert seen[:save].last, "the save ran without the entry lock"
  end

  # The save now runs inside the lock's transaction, so a unique-index
  # collision must still come back as a 422, not abort that transaction.
  test "create under the lock still reports an existing bill with the same identity" do
    entry = accounts(:depository).entries.create!(
      date: Date.current, amount: 100, currency: "USD", name: "FRESH CHARGE",
      entryable: Transaction.new(merchant: covering_merchant)
    )
    @family.recurring_transactions.create!(
      account: accounts(:depository), name: "Household Plan", amount: 100, currency: "USD",
      dedup_scope: BigDecimal("100").to_s("F"), expected_day_of_month: Date.current.day,
      last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,
      status: "active", manual: true, occurrence_count: 0
    )
    params = covered_create_params(entry)
    params[:recurring_transaction][:name] = "Household Plan"

    assert_no_difference "RecurringTransaction.count" do
      post recurring_transactions_url, params: params
    end

    assert_response :unprocessable_entity
    assert_match I18n.t("recurring_transactions.create.already_exists"), response.body
  end

  private

    # The Allocator's two-key advisory lock on this entry, held by this session.
    def entry_lock_held?(entry)
      ActiveRecord::Base.connection.select_value(ActiveRecord::Base.sanitize_sql_array([ <<~SQL, RecurringTransaction::Allocator::ENTRY_LOCK_NAMESPACE, RecurringTransaction::Allocator.entry_lock_id(entry) ]))
        SELECT EXISTS (
          SELECT 1 FROM pg_locks
          WHERE locktype = 'advisory' AND pid = pg_backend_pid() AND granted
            AND classid = ? AND objid = ? AND objsubid = 2
        )
      SQL
    end

    def covering_merchant
      @covering_merchant ||= @family.merchants.create!(name: "Betashares")
    end

    def covered_entry_and_detected_bill(status: "active", account: accounts(:depository))
      entry = account.entries.create!(
        date: Date.current, amount: 100, currency: account.currency, name: "BETASHARES DIRECT DEBIT",
        entryable: Transaction.new(merchant: covering_merchant)
      )
      detected = @family.recurring_transactions.create!(
        account: account, merchant: covering_merchant, name: nil,
        amount: 100, currency: account.currency, expected_day_of_month: Date.current.day,
        last_occurrence_date: 1.month.ago.to_date, next_expected_date: Date.current,
        status: status, manual: false, occurrence_count: 2
      )
      [ entry, detected ]
    end

    # What the prefilled dialog posts: the merchant's name, never its id.
    def covered_create_params(entry)
      {
        entry_id: entry.id,
        recurring_transaction: {
          name: "Betashares",
          amount: "100",
          account_id: accounts(:depository).id,
          first_due_on: (Date.current + 1.month).iso8601,
          frequency_preset: "monthly"
        }
      }
    end

    def create_series(name:, account: accounts(:depository), merchant: nil, status: "active", payment_url: nil,
                      amount: 25, bill_type: "bill")
      @family.recurring_transactions.create!(
        account: account,
        merchant: merchant,
        name: name,
        amount: amount,
        bill_type: bill_type,
        dedup_scope: name,
        currency: "USD",
        expected_day_of_month: 5,
        last_occurrence_date: 1.month.ago.to_date,
        next_expected_date: 5.days.from_now.to_date,
        status: status,
        payment_url: payment_url
      )
    end

    def picker_entry(name:, amount:, account: accounts(:depository), merchant: nil, notes: nil, kind: nil, excluded: false)
      transaction_attrs = { merchant: merchant }
      transaction_attrs[:kind] = kind if kind

      account.entries.create!(
        date: Date.current, amount: amount, currency: "USD", name: name,
        notes: notes, excluded: excluded,
        entryable: Transaction.new(**transaction_attrs)
      )
    end

    # A detected bill with a payment two cycles back: before the current cycle
    # whatever day the suite runs, so only a history pass can link it.
    def suggested_bill_with_past_payment
      paid_on = Date.current.beginning_of_month + 8.days - 2.months
      suggestion = @family.recurring_transactions.create!(
        name: "CITY WATER", account: accounts(:depository), amount: 80, currency: "USD",
        expected_day_of_month: 9, last_occurrence_date: paid_on,
        next_expected_date: paid_on + 2.months, status: "suggested", manual: false
      )
      entry = accounts(:depository).entries.create!(
        date: paid_on, amount: 80, currency: "USD", name: "CITY WATER",
        entryable: Transaction.new
      )

      [ paid_on, suggestion, entry ]
    end
end