Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
31.7 KB
Raw Blame
require "test_helper"

class ImportsControllerTest < ActionDispatch::IntegrationTest
  include ActiveJob::TestHelper

  setup do
    sign_in @user = users(:family_admin)
    ensure_tailwind_build
  end

  test "gets index" do
    get imports_url

    assert_response :success

    @user.family.imports.ordered.each do |import|
      assert_select "#" + dom_id(import), count: 1
    end
  end

  test "gets new" do
    adapter = mock("vector_store_adapter")
    adapter.stubs(:supported_extensions).returns(%w[.pdf .txt])
    VectorStore::Registry.stubs(:adapter).returns(adapter)
    use_ai_routes

    get new_import_url

    assert_response :success

    assert_select "turbo-frame#modal"
    # The file inputs submit through the auto-submit-form controller rather
    # than an inline onchange handler, which the Content Security Policy blocks.
    assert_select "form[data-turbo-frame=_top][data-controller~=auto-submit-form] input[type=file][data-auto-submit-form-target=auto]", count: 2
    assert_select "input[type=file][onchange]", count: 0
  end

  # DS::Button with an href renders button_to, which POSTs unless given a
  # method. revert only routes PUT, so Try again hit a routing error.
  test "try again on a failed revert PUTs to revert" do
    import = imports(:transaction)
    import.update_columns(status: "revert_failed")
    TransactionImport.any_instance.stubs(uploaded?: true, publishable?: true)

    get import_url(import)

    assert_response :success
    assert_select "form[action=?]", revert_import_path(import) do
      assert_select "input[name=_method][value=put]"
    end
  end

  # POSTing to imports_path is create, which needs import params.
  test "back to imports on an empty import is a link to the imports page" do
    import = imports(:transaction)
    TransactionImport.any_instance.stubs(uploaded?: true, publishable?: true)

    get import_url(import)

    assert_response :success
    assert_select "a[href=?]", imports_path, text: I18n.t("imports.ready.back_to_imports")
    assert_select "form[action=?]", imports_path, count: 0
  end

  test "cancel marks a lost import as failed" do
    import = imports(:transaction)
    import.update_columns(status: "importing", updated_at: 2.hours.ago)

    post cancel_import_path(import)

    assert_redirected_to imports_path
    assert_equal "failed", import.reload.status
    assert_equal Import.lost_error_message, import.error
  end

  test "cancel refuses an import that is not presumed lost" do
    import = imports(:transaction)
    import.update_columns(status: "importing", updated_at: 5.minutes.ago)

    post cancel_import_path(import)

    assert_equal I18n.t("imports.cancel.not_cancellable"), flash[:alert]
    assert_equal "importing", import.reload.status
  end

  test "cannot cancel another family's import" do
    import = imports(:transaction)
    import.update_columns(status: "importing", updated_at: 2.hours.ago)

    sign_in users(:empty)

    post cancel_import_path(import)

    assert_response :not_found
    assert_equal "importing", import.reload.status
  end

  test "shows disabled account-dependent imports when family has no accounts" do
    sign_in users(:empty)

    get new_import_url

    assert_response :success
    assert_select "button", text: "Import accounts"
    assert_select "button", text: "Import transactions", count: 0
    assert_select "button", text: "Import investments", count: 0
    assert_select "button", text: "Import from Mint", count: 1
    assert_select "button", text: "Import from Actual Budget", count: 1
    assert_select "button", text: "Import from Quicken (QIF)", count: 1
    assert_select "button", text: "Import from YNAB", count: 1
    assert_select "span", text: "Import accounts first to unlock this option.", count: 2
    assert_select "div[aria-disabled=true]", count: 2
  end

  test "creates import" do
    assert_difference "Import.count", 1 do
      post imports_url, params: {
        import: {
          type: "TransactionImport"
        }
      }
    end

    assert_redirected_to import_upload_url(Import.all.ordered.first)
  end

  test "dropping a Sure transactions.csv export presets the export sign convention" do
    exported_csv = "#{Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")}\n2024-05-15,Checking Account,42.5,Grocery,,,,USD\n"

    post imports_url, params: {
      import: {
        type: "TransactionImport",
        import_file: Rack::Test::UploadedFile.new(StringIO.new(exported_csv), "text/csv", original_filename: "transactions.csv")
      }
    }

    import = Import.all.ordered.first
    assert_redirected_to import_configuration_url(import)
    assert_equal "inflows_negative", import.signage_convention
    assert_equal "%Y-%m-%d", import.date_format
  end

  test "dropping a CSV with non-ASCII characters presets by header and does not fail" do
    header = Family::DataExporter::TRANSACTIONS_CSV_HEADERS.join(",")
    [ "#{header}\n2024-05-15,Checking Account,42.5,Café,,,,USD\n", "\uFEFFdate,amount,name\n2024-05-15,5,Café\n" ].each do |csv|
      file = Tempfile.new([ "upload", ".csv" ], binmode: true)
      file.write(csv)
      file.rewind

      assert_difference "Import.count", 1 do
        post imports_url, params: {
          import: { type: "TransactionImport", import_file: Rack::Test::UploadedFile.new(file.path, "text/csv") }
        }
      end

      import = Import.all.ordered.first
      assert_redirected_to import_configuration_url(import)
      assert_equal csv.start_with?(header) ? "inflows_negative" : "inflows_positive", import.signage_convention
    ensure
      file&.close!
    end
  end

  test "create with an empty request body redirects back with an alert" do
    assert_no_difference "Import.count" do
      post imports_url
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("imports.create.missing_upload"), flash[:alert]
  end

  test "create with DocumentImport or SureImport type but no file redirects back with an alert" do
    %w[DocumentImport SureImport].each do |type|
      assert_no_difference "Import.count" do
        post imports_url, params: { import: { type: type } }
      end

      assert_redirected_to new_import_url
      assert_equal I18n.t("imports.create.missing_upload"), flash[:alert]
    end
  end

  test "uploads supported non-pdf document for vector store without creating import" do
    adapter = mock("vector_store_adapter")
    adapter.stubs(:supported_extensions).returns(%w[.csv .pdf])
    VectorStore::Registry.stubs(:adapter).returns(adapter)
    use_ai_routes

    family_document = family_documents(:tax_return)
    Family.any_instance.expects(:upload_document).with do |file_content:, filename:, **|
      assert_not_empty file_content
      assert_equal "valid.csv", filename
      true
    end.returns(family_document)

    assert_no_difference "Import.count" do
      post imports_url, params: {
        import: {
          type: "DocumentImport",
          import_file: file_fixture_upload("imports/valid.csv", "text/csv")
        }
      }
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("imports.create.document_uploaded"), flash[:notice]
  end

  test "summary renders the import outcome for a pdf import" do
    get summary_import_url(imports(:pdf_with_rows))

    assert_response :success
    assert_select "dialog"
  end

  test "summary is not available for non-pdf imports" do
    get summary_import_url(imports(:transaction))

    assert_response :not_found
  end

  test "uploads pdf document as PdfImport when using DocumentImport option" do
    adapter = mock("vector_store_adapter")
    adapter.stubs(:supported_extensions).returns(%w[.pdf .txt])
    VectorStore::Registry.stubs(:adapter).returns(adapter)
    use_ai_routes

    @user.family.expects(:upload_document).never

    assert_difference "Import.count", 1 do
      assert_difference "AccountStatement.count", 1 do
        post imports_url, params: {
          import: {
            type: "DocumentImport",
            import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
          }
        }
      end
    end

    created_import = Import.order(:created_at).last
    assert_equal "PdfImport", created_import.type
    assert_equal AccountStatement.order(:created_at).last, created_import.account_statement
    assert_not created_import.pdf_file.attached?
    assert_redirected_to import_url(created_import)
    assert_equal I18n.t("imports.create.pdf_processing"), flash[:notice]
  end

  test "uploads pdf import through account statement" do
    assert_difference "AccountStatement.count", 1 do
      assert_difference "Import.where(type: 'PdfImport').count", 1 do
        post imports_url, params: {
          import: {
            import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
          }
        }
      end
    end

    statement = AccountStatement.order(:created_at).last
    created_import = PdfImport.order(:created_at).last
    assert_equal statement, created_import.account_statement
    assert_not created_import.pdf_file.attached?
    assert_redirected_to import_url(created_import)
    assert_equal I18n.t("imports.create.pdf_processing"), flash[:notice]
  end

  test "guest cannot create statement backed pdf import" do
    sign_in users(:intro_user)

    assert_no_difference [ "AccountStatement.count", "Import.where(type: 'PdfImport').count" ] do
      assert_no_enqueued_jobs only: ProcessPdfJob do
        post imports_url, params: {
          import: {
            import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
          }
        }
      end
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
  end

  test "duplicate pdf import reuses account statement" do
    statement = AccountStatement.create_from_upload!(
      family: @user.family,
      account: nil,
      file: uploaded_file(
        filename: "existing_statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )

    assert_no_difference "AccountStatement.count" do
      assert_difference "Import.where(type: 'PdfImport').count", 1 do
        post imports_url, params: {
          import: {
            import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
          }
        }
      end
    end

    created_import = PdfImport.order(:created_at).last
    assert_equal statement, created_import.account_statement
    assert_redirected_to import_url(created_import)
  end

  test "duplicate pdf import does not enqueue processing twice for reused import" do
    assert_difference "AccountStatement.count", 1 do
      assert_difference "Import.where(type: 'PdfImport').count", 1 do
        assert_enqueued_jobs 1, only: ProcessPdfJob do
          post imports_url, params: {
            import: {
              import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
            }
          }

          post imports_url, params: {
            import: {
              import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
            }
          }
        end
      end
    end

    created_import = PdfImport.order(:created_at).last
    assert_equal "importing", created_import.status
    assert_redirected_to import_url(created_import)
  end

  test "duplicate pdf import for inaccessible statement does not create import" do
    AccountStatement.create_from_upload!(
      family: @user.family,
      account: accounts(:investment),
      file: uploaded_file(
        filename: "existing_statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )

    sign_in users(:family_member)

    assert_no_difference [ "AccountStatement.count", "Import.where(type: 'PdfImport').count" ] do
      post imports_url, params: {
        import: {
          import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
        }
      }
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("imports.create.duplicate_pdf_unavailable"), flash[:alert]
  end

  test "read only shared user cannot reuse duplicate statement backed pdf import" do
    AccountStatement.create_from_upload!(
      family: @user.family,
      account: accounts(:credit_card),
      file: uploaded_file(
        filename: "existing_statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )

    sign_in users(:family_member)

    assert_no_difference [ "AccountStatement.count", "Import.where(type: 'PdfImport').count" ] do
      assert_no_enqueued_jobs only: ProcessPdfJob do
        post imports_url, params: {
          import: {
            import_file: file_fixture_upload("imports/sample_bank_statement.pdf", "application/pdf")
          }
        }
      end
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("imports.create.duplicate_pdf_unavailable"), flash[:alert]
  end

  test "setting statement backed pdf import account links source statement" do
    statement = AccountStatement.create_from_upload!(
      family: @user.family,
      account: nil,
      file: uploaded_file(
        filename: "statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )
    pdf_import = PdfImport.create_from_statement!(statement: statement)
    account = accounts(:depository)

    patch import_url(pdf_import), params: { import: { account_id: account.id } }

    assert_redirected_to import_url(pdf_import)
    assert_equal I18n.t("imports.update.account_saved", default: "Account saved."), flash[:notice]
    assert_equal account, pdf_import.reload.account
    assert_equal account, statement.reload.account
  end

  test "read only shared user cannot link source statement through pdf import account update" do
    account = accounts(:credit_card)
    statement = AccountStatement.create_from_upload!(
      family: @user.family,
      account: nil,
      file: uploaded_file(
        filename: "statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )
    pdf_import = PdfImport.create_from_statement!(statement: statement)

    sign_in users(:family_member)
    patch import_url(pdf_import), params: { import: { account_id: account.id } }

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
    assert_nil pdf_import.reload.account
    assert_nil statement.reload.account
  end

  test "user cannot view statement backed pdf import for inaccessible statement" do
    statement = AccountStatement.create_from_upload!(
      family: @user.family,
      account: accounts(:investment),
      file: uploaded_file(
        filename: "statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )
    pdf_import = PdfImport.create_from_statement!(statement: statement)

    sign_in users(:family_member)
    get import_url(pdf_import)

    assert_response :not_found
  end

  test "import pages hide a statement backed pdf import for an inaccessible statement" do
    statement = AccountStatement.create_from_upload!(
      family: @user.family,
      account: accounts(:investment),
      file: uploaded_file(
        filename: "statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )
    pdf_import = PdfImport.create_from_statement!(statement: statement)
    row = pdf_import.rows.create!(source_row_number: 1, date: "01-15-2024", amount: "-42.00", currency: "USD", name: "Statement line")

    sign_in users(:family_member)

    get imports_url
    assert_response :success
    assert_select "#" + dom_id(pdf_import), count: 0
    assert_select "#" + dom_id(imports(:transaction)), count: 1

    get new_import_url
    assert_response :success
    assert_select "a[href='#{import_path(pdf_import)}']", count: 0

    [
      import_row_path(pdf_import, row),
      import_clean_path(pdf_import),
      import_confirm_path(pdf_import),
      import_upload_path(pdf_import),
      import_configuration_path(pdf_import),
      import_qif_category_selection_path(pdf_import)
    ].each do |path|
      get path
      assert_response :not_found, path
    end

    patch import_row_path(pdf_import, row), params: { import_row: { name: "Changed" } }
    assert_response :not_found
    mapping = Import::CategoryMapping.create!(import: pdf_import, key: "Groceries")
    patch import_mapping_path(pdf_import, mapping), params: { import_mapping: { mappable_id: categories(:food_and_drink).id } }
    assert_response :not_found
    assert_equal "Statement line", row.reload.name
    assert_nil mapping.reload.mappable
  end

  test "read only shared user cannot publish statement backed pdf import" do
    account = accounts(:credit_card)
    statement = AccountStatement.create_from_upload!(
      family: @user.family,
      account: account,
      file: uploaded_file(
        filename: "statement.pdf",
        content_type: "application/pdf",
        content: file_fixture("imports/sample_bank_statement.pdf").binread
      )
    )
    pdf_import = PdfImport.create_from_statement!(statement: statement)
    PdfImport.any_instance.expects(:publish_later).never

    sign_in users(:family_member)
    post publish_import_url(pdf_import)

    assert_redirected_to account_url(account)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
  end

  test "a document upload is refused with the router's reason when embed isn't available" do
    use_no_ai

    assert_no_difference "Import.count" do
      post imports_url, params: { import: { type: "DocumentImport", import_file: file_fixture_upload("imports/valid.csv", "text/csv") } }
    end

    assert_redirected_to new_import_url
    assert_equal Ai::Availability.unavailable(:embed, :not_configured).message_for(@user), flash[:alert]
  end

  test "a document upload by a user with AI off sends nothing to the vector store" do
    use_ai_routes
    @user.update!(ai_enabled: false)
    Family.any_instance.expects(:upload_document).never

    post imports_url, params: { import: { type: "DocumentImport", import_file: file_fixture_upload("imports/valid.csv", "text/csv") } }

    assert_redirected_to new_import_url
    assert_equal Ai::Availability.unavailable(:embed, :user_disabled).message_for(@user), flash[:alert]
  end

  test "a document upload says no store is configured when the embed route is set but the store can't be built" do
    VectorStore::Registry.stubs(:adapter).returns(nil)
    use_ai_routes

    assert_no_difference "Import.count" do
      post imports_url, params: { import: { type: "DocumentImport", import_file: file_fixture_upload("imports/valid.csv", "text/csv") } }
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("imports.create.document_provider_not_configured"), flash[:alert]
  end

  test "rejects unsupported document type for DocumentImport option" do
    adapter = mock("vector_store_adapter")
    adapter.stubs(:supported_extensions).returns(%w[.pdf .txt])
    VectorStore::Registry.stubs(:adapter).returns(adapter)
    use_ai_routes

    assert_no_difference "Import.count" do
      post imports_url, params: {
        import: {
          type: "DocumentImport",
          import_file: file_fixture_upload("profile_image.png", "image/png")
        }
      }
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("imports.create.invalid_document_file_type"), flash[:alert]
  end

  test "publishes import" do
    import = imports(:transaction)

    TransactionImport.any_instance.expects(:publish_later).once

    post publish_import_url(import)

    assert_equal "Your import has started in the background.", flash[:notice]
    assert_redirected_to import_path(import)
  end

  test "member cannot publish import targeting a read only shared account" do
    import = imports(:transaction)
    import.update!(account: accounts(:credit_card))
    TransactionImport.any_instance.expects(:publish_later).never

    sign_in users(:family_member)
    post publish_import_url(import)

    assert_redirected_to import_path(import)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
  end

  test "member cannot publish import with account mapping to an unshared account" do
    import = imports(:transaction)
    import.mappings.create!(type: "Import::AccountMapping", key: "Brokerage", mappable: accounts(:investment))
    TransactionImport.any_instance.expects(:publish_later).never

    sign_in users(:family_member)
    post publish_import_url(import)

    assert_redirected_to import_path(import)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
  end

  test "member can publish import targeting a full control shared account" do
    import = imports(:transaction)
    import.update!(account: accounts(:depository))
    import.mappings.create!(type: "Import::AccountMapping", key: "Checking", mappable: accounts(:depository))
    TransactionImport.any_instance.expects(:publish_later).once

    sign_in users(:family_member)
    post publish_import_url(import)

    assert_redirected_to import_path(import)
    assert_equal I18n.t("imports.publish.started"), flash[:notice]
  end

  test "member cannot revert import whose entries are in a read only shared account" do
    import = imports(:transaction)
    import.update!(status: :complete)
    entries(:transaction).update!(import: import, account: accounts(:credit_card))
    TransactionImport.any_instance.expects(:revert_later).never

    sign_in users(:family_member)
    put revert_import_url(import)

    assert_redirected_to import_path(import)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
  end

  test "member cannot delete import whose entries are in a read only shared account" do
    import = imports(:transaction)
    import.update!(status: :failed)
    entries(:transaction).update!(import: import, account: accounts(:credit_card))

    sign_in users(:family_member)
    assert_no_difference([ "Import.count", "Entry.count" ]) do
      delete import_url(import)
    end

    assert_redirected_to import_path(import)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
  end

  test "member cannot publish QIF import whose embedded account matches a read only shared account" do
    import = qif_import_with_embedded_account(accounts(:credit_card).name)
    QifImport.any_instance.expects(:publish_later).never

    sign_in users(:family_member)
    post publish_import_url(import)

    assert_redirected_to import_path(import)
    assert_equal I18n.t("accounts.not_authorized"), flash[:alert]
  end

  test "member can publish QIF import whose embedded account is new" do
    import = qif_import_with_embedded_account("Brand New QIF Account")
    QifImport.any_instance.expects(:publish_later).once

    sign_in users(:family_member)
    post publish_import_url(import)

    assert_redirected_to import_path(import)
    assert_equal I18n.t("imports.publish.started"), flash[:notice]
  end

  test "destroys import" do
    import = imports(:transaction)

    assert_difference "Import.count", -1 do
      delete import_url(import)
    end

    assert_redirected_to imports_path
  end

  test "respects SURE_IMPORT_MAX_NDJSON_SIZE_MB when creating Sure import (#3010)" do
    configured_limit = 2.megabytes
    SureImport.stubs(:max_ndjson_size).returns(configured_limit)

    oversized_file = Rack::Test::UploadedFile.new(
      StringIO.new("x" * (configured_limit + 1)),
      "application/x-ndjson",
      original_filename: "all.ndjson"
    )

    assert_no_difference "Import.count" do
      post imports_url, params: {
        import: {
          type: "SureImport",
          import_file: oversized_file
        }
      }
    end

    assert_redirected_to new_import_url
    assert_equal I18n.t("imports.create.file_too_large", max_size: configured_limit / 1.megabyte), flash[:alert]
  end

  test "shows a friendly warning when a Sure import's transactions reference merchants missing from the export (#3113)" do
    import = @user.family.imports.create!(type: "SureImport")
    ndjson = [
      { type: "Account", data: {
        id: "account-1", name: "Old Export Checking", balance: "1000.00", currency: "USD",
        accountable_type: "Depository", accountable: { subtype: "checking" }
      } },
      { type: "Transaction", data: {
        id: "transaction-1", account_id: "account-1", merchant_id: "merchant-never-exported",
        date: "2024-01-15", amount: "42.50", name: "Amazon purchase", currency: "USD"
      } }
    ].map(&:to_json).join("\n")
    import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
    import.sync_ndjson_rows_count!

    get import_url(import)

    assert_response :success
    assert_includes response.body, I18n.t("imports.ready.missing_merchant_warning_title")
  end

  test "does not show the missing merchant warning for a Sure import with no unresolved merchant references" do
    import = @user.family.imports.create!(type: "SureImport")
    ndjson = [
      { type: "Account", data: {
        id: "account-1", name: "Clean Export Checking", balance: "1000.00", currency: "USD",
        accountable_type: "Depository", accountable: { subtype: "checking" }
      } }
    ].map(&:to_json).join("\n")
    import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
    import.sync_ndjson_rows_count!

    get import_url(import)

    assert_response :success
    assert_not_includes response.body, I18n.t("imports.ready.missing_merchant_warning_title")
  end

  test "explains that unnamed recurring transactions with a missing merchant will be skipped" do
    import = @user.family.imports.create!(type: "SureImport")
    ndjson = [
      { type: "Account", data: {
        id: "account-1", name: "Checking", balance: "1000.00", currency: "USD",
        accountable_type: "Depository", accountable: { subtype: "checking" }
      } },
      { type: "RecurringTransaction", data: {
        id: "recurring-1", account_id: "account-1", merchant_id: "merchant-never-exported",
        amount: "11.99", currency: "USD", expected_day_of_month: 28,
        last_occurrence_date: "2026-08-28", next_expected_date: "2026-09-28"
      } }
    ].map(&:to_json).join("\n")
    import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
    import.sync_ndjson_rows_count!

    get import_url(import)

    assert_response :success
    assert_includes response.body, I18n.t("imports.ready.missing_merchant_warning_title")
    assert_includes response.body, I18n.t("imports.ready.skipped_recurring_description", count: 1).squish
    assert_not_includes response.body, "merchant reference in this file"
  end

  test "shows a friendly notice when a Sure import reuses existing categories, tags or merchants by name (#3113)" do
    @user.family.categories.create!(name: "Groceries", color: "#407706", lucide_icon: "shopping-basket")
    import = @user.family.imports.create!(type: "SureImport")
    ndjson = [
      { type: "Category", data: { id: "category-1", name: "Groceries" } }
    ].map(&:to_json).join("\n")
    import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
    import.sync_ndjson_rows_count!

    get import_url(import)

    assert_response :success
    assert_includes response.body, I18n.t("imports.ready.reused_taxonomy_notice_title")
  end

  test "does not show the reused taxonomy notice for a Sure import with no name collisions" do
    import = @user.family.imports.create!(type: "SureImport")
    ndjson = [
      { type: "Category", data: { id: "category-1", name: "A Brand New Category Name" } }
    ].map(&:to_json).join("\n")
    import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
    import.sync_ndjson_rows_count!

    get import_url(import)

    assert_response :success
    assert_not_includes response.body, I18n.t("imports.ready.reused_taxonomy_notice_title")
  end

  test "shows the differences when an existing provider merchant differs from the Sure import file" do
    ProviderMerchant.create!(name: "AMZN MKTP", source: "plaid", website_url: "https://amazon.com")
    import = @user.family.imports.create!(type: "SureImport")
    ndjson = [
      { type: "Account", data: {
        id: "account-1", name: "Checking", balance: "1000.00", currency: "USD",
        accountable_type: "Depository", accountable: { subtype: "checking" }
      } },
      { type: "ProviderMerchant", data: { id: "pm-1", name: "AMZN MKTP", source: "plaid", website_url: "https://amazon.co.uk" } }
    ].map(&:to_json).join("\n")
    import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
    import.sync_ndjson_rows_count!

    get import_url(import)

    assert_response :success
    assert_includes response.body, I18n.t("imports.ready.provider_merchant_diff_title")
    assert_includes response.body, "AMZN MKTP"
    assert_includes response.body, "keeping https://amazon.com, file has https://amazon.co.uk"
  end

  test "does not show the provider merchant differences notice without a difference" do
    import = @user.family.imports.create!(type: "SureImport")
    ndjson = [
      { type: "Account", data: {
        id: "account-1", name: "Checking", balance: "1000.00", currency: "USD",
        accountable_type: "Depository", accountable: { subtype: "checking" }
      } }
    ].map(&:to_json).join("\n")
    import.ndjson_file.attach(io: StringIO.new(ndjson), filename: "all.ndjson", content_type: "application/x-ndjson")
    import.sync_ndjson_rows_count!

    get import_url(import)

    assert_response :success
    assert_not_includes response.body, I18n.t("imports.ready.provider_merchant_diff_title")
  end

  test "import ready notices use singular and plural wording" do
    {
      "imports.ready.missing_merchant_warning_description" => [ "1 merchant reference in this file", "2 merchant references in this file" ],
      "imports.ready.reused_taxonomy_notice_description" => [ "1 category, tag or merchant", "2 categories, tags or merchants" ],
      "imports.ready.provider_merchant_diff_description" => [ "1 merchant in this file", "2 merchants in this file" ]
    }.each do |key, (singular, plural)|
      assert_includes I18n.t(key, count: 1), singular
      assert_includes I18n.t(key, count: 2), plural
    end
  end

  test "PDF import account select does not leak unshared family accounts (#1803)" do
    sign_in users(:family_member)
    pdf_import = imports(:pdf_with_rows)
    # The fixture has no attached pdf_file and no statement, so
    # ImportsController#show would redirect to the upload page. The
    # partial under test only renders for an uploaded PDF — stub the
    # state so we exercise the actual account-select scoping path.
    PdfImport.any_instance.stubs(:pdf_uploaded?).returns(true)

    get import_url(pdf_import)

    assert_response :success
    assert_select 'select[name="import[account_id]"] option', text: "Checking Account"
    assert_select 'select[name="import[account_id]"] option', text: "Collectable Account", count: 0
    assert_select 'select[name="import[account_id]"] option', text: "IOU (personal debt to friend)", count: 0
    assert_select 'select[name="import[account_id]"] option', text: "Plaid Depository Account", count: 0
  end

  private
    def qif_import_with_embedded_account(name)
      import = QifImport.create!(family: families(:dylan_family))
      import.update!(raw_file_str: <<~QIF)
        !Account
        N#{name}
        TBank
        ^
        !Type:Bank
        D1/ 1'24
        U-25.00
        T-25.00
        PCoffee Shop
        ^
      QIF
      import.generate_rows_from_csv
      import.reload
    end
end