Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
60.7 KB
Raw Blame
require "test_helper"
require "ostruct"

class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCase
  setup do
    @family = families(:dylan_family)
    @account = accounts(:depository)
    @enable_banking_item = EnableBankingItem.create!(
      family: @family,
      name: "Test Enable Banking",
      country_code: "DE",
      application_id: "test_app_id",
      client_certificate: "test_cert"
    )
    @enable_banking_account = EnableBankingAccount.create!(
      enable_banking_item: @enable_banking_item,
      name: "N26 Hauptkonto",
      uid: "eb_uid_1",
      currency: "EUR"
    )
    AccountProvider.create!(
      account: @account,
      provider: @enable_banking_account
    )
  end

  test "uses entry_reference as external_id when transaction_id is nil" do
    tx = {
      entry_reference: "31e13269-03fc-11f1-89d2-cd465703551c",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "11.65", currency: "EUR" },
      creditor: { name: "Spar Dankt 3418" },
      credit_debit_indicator: "DBIT",
      status: "BOOK"
    }

    assert_difference "@account.entries.count", 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    entry = @account.entries.find_by!(
      external_id: "enable_banking_31e13269-03fc-11f1-89d2-cd465703551c",
      source: "enable_banking"
    )
    assert_equal 11.65, entry.amount.to_f
    assert_equal "EUR", entry.currency
  end

  test "uses transaction_id as external_id when present" do
    tx = {
      entry_reference: "ref_123",
      transaction_id: "txn_456",
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "25.00", currency: "EUR" },
      creditor: { name: "Amazon" },
      credit_debit_indicator: "DBIT",
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process

    entry = @account.entries.find_by!(external_id: "enable_banking_txn_456", source: "enable_banking")
    assert_equal 25.0, entry.amount.to_f
  end

  test "does not create duplicate when same entry_reference is processed twice" do
    tx = {
      entry_reference: "unique_ref_abc",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "50.00", currency: "EUR" },
      creditor: { name: "Rewe" },
      credit_debit_indicator: "DBIT",
      status: "BOOK"
    }

    assert_difference "@account.entries.count", 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    assert_no_difference "@account.entries.count" do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end
  end

  # --- compute_external_id unit tests ---

  test "compute_external_id returns transaction_id-based id when present" do
    assert_equal "enable_banking_txn_abc",
      EnableBankingEntry::Processor.compute_external_id(transaction_id: "txn_abc", entry_reference: "ref_xyz")
  end

  test "compute_external_id falls back to entry_reference when transaction_id is blank" do
    assert_equal "enable_banking_ref_xyz",
      EnableBankingEntry::Processor.compute_external_id(transaction_id: nil, entry_reference: "ref_xyz")
  end

  test "compute_external_id returns content fingerprint when both id fields are absent" do
    tx = {
      booking_date: "2026-03-15",
      transaction_amount: { amount: "42.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: { name: "Spar" }
    }
    result = EnableBankingEntry::Processor.compute_external_id(tx)
    assert result.start_with?("enable_banking_content_"), "Expected content fingerprint, got: #{result}"
  end

  test "compute_external_id fingerprint is stable across calls" do
    tx = {
      booking_date: "2026-03-15",
      transaction_amount: { amount: "42.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: { name: "Spar" }
    }
    assert_equal EnableBankingEntry::Processor.compute_external_id(tx),
                 EnableBankingEntry::Processor.compute_external_id(tx)
  end

  test "compute_external_id returns nil for transaction with no identifiable content" do
    assert_nil EnableBankingEntry::Processor.compute_external_id({})
    assert_nil EnableBankingEntry::Processor.compute_external_id(transaction_id: nil, entry_reference: nil)
  end

  # --- ID-less transaction processing ---

  test "imports transaction using content fingerprint when transaction_id and entry_reference are absent" do
    tx = {
      transaction_id: nil,
      entry_reference: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "10.00", currency: "EUR" },
      creditor: { name: "Lidl" },
      credit_debit_indicator: "DBIT",
      status: "BOOK"
    }

    assert_difference "@account.entries.count", 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    expected_id = EnableBankingEntry::Processor.compute_external_id(tx)
    assert @account.entries.exists?(external_id: expected_id, source: "enable_banking")
  end

  test "does not create duplicate when same id-less transaction is processed twice" do
    tx = {
      transaction_id: nil,
      entry_reference: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "10.00", currency: "EUR" },
      creditor: { name: "Lidl" },
      credit_debit_indicator: "DBIT",
      status: "BOOK"
    }

    assert_difference "@account.entries.count", 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    assert_no_difference "@account.entries.count" do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end
  end

  test "raises ArgumentError for transaction with no identifiable content at all" do
    tx = { transaction_id: nil, entry_reference: nil }

    assert_raises(ArgumentError) do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end
  end

  test "handles string keys in transaction data" do
    tx = {
      "entry_reference" => "string_key_ref",
      "transaction_id" => nil,
      "booking_date" => Date.current.to_s,
      "transaction_amount" => { "amount" => "15.00", "currency" => "EUR" },
      "creditor" => { "name" => "Lidl" },
      "credit_debit_indicator" => "DBIT",
      "status" => "BOOK"
    }

    assert_difference "@account.entries.count", 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    entry = @account.entries.find_by!(external_id: "enable_banking_string_key_ref", source: "enable_banking")
    assert_equal 15.0, entry.amount.to_f
  end

  test "includes note field in transaction notes alongside remittance_information" do
    tx = {
      entry_reference: "ref_note",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "10.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      remittance_information: [ "Facture 2026-001" ],
      note: "Détail comptable interne",
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_note")
    assert_includes entry.notes, "Facture 2026-001"
    assert_includes entry.notes, "Détail comptable interne"
  end

  test "imports transaction with real merchant name instead of generic POS terminal line (issue #2935)" do
    tx = {
      entry_reference: "ref_pos_2935",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "45.13", currency: "EUR" },
      creditor: { name: "" },
      debtor: nil,
      bank_transaction_code: nil,
      credit_debit_indicator: "DBIT",
      remittance_information: [
        "POS          45,13 AT  D6   31.07. 10:27",
        "BILLA DANKT 0007114"
      ],
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_pos_2935")
    assert_equal "BILLA DANKT 0007114", entry.name
    assert_includes entry.notes, "POS          45,13 AT  D6   31.07. 10:27"
  end

  test "uses the family's known merchant name instead of the raw remittance line when it matches, and assigns the merchant" do
    @family.merchants.create!(name: "Billa")

    tx = {
      entry_reference: "ref_known_merchant",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "45.13", currency: "EUR" },
      creditor: { name: "" },
      bank_transaction_code: nil,
      credit_debit_indicator: "DBIT",
      remittance_information: [
        "POS          45,13 AT  D6   31.07. 10:27",
        "BILLA DANKT 0007114"
      ],
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_known_merchant")

    assert_equal "Billa", entry.name
    assert_equal "Billa", entry.transaction.merchant&.name
  end

  test "does not take the account holder's name at the end of a card payment as the merchant" do
    @family.merchants.create!(name: "Jane Doe")
    @enable_banking_account.update!(raw_payload: { "uid" => "eb_uid_1", "name" => "JANE DOE" })

    tx = {
      entry_reference: "ref_cardholder_name",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "12.50", currency: "EUR" },
      bank_transaction_code: { code: "PMNT" },
      credit_debit_indicator: "DBIT",
      remittance_information: [ "EXAMPLE SHOP 1000 CITY Card payment 05-08-2026 13.07 1234 56XX XXXX 7890 JANE DOE" ],
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_cardholder_name")

    assert_nil entry.transaction.merchant
    assert_not_equal "Jane Doe", entry.name
  end

  test "does not match the paying side of a transaction as a known merchant" do
    # The holder's name is the longer match, so only the holder check keeps it out.
    @family.merchants.create!(name: "Jane Elizabeth Doe")
    @family.merchants.create!(name: "Example Shop")

    name = build_name_with_family(
      credit_debit_indicator: "DBIT",
      debtor: { name: "JANE ELIZABETH DOE" },
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "EXAMPLE SHOP 1000 CITY Card payment JANE ELIZABETH DOE" ]
    )

    assert_equal "Example Shop", name
  end

  test "does not assign the holder as merchant when the remittance is only the holder's name" do
    @family.merchants.create!(name: "Jane Doe")
    @enable_banking_account.update!(raw_payload: { "uid" => "eb_uid_1", "name" => "JANE DOE" })

    tx = {
      entry_reference: "ref_holder_only_remittance",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "8.00", currency: "EUR" },
      creditor: { name: "" },
      bank_transaction_code: nil,
      credit_debit_indicator: "DBIT",
      remittance_information: [ "Jane Doe" ],
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process

    assert_nil @account.entries.find_by!(external_id: "enable_banking_ref_holder_only_remittance").transaction.merchant
  end

  test "does not pick a known merchant out of a remittance that is only the holder's name" do
    @family.merchants.create!(name: "Jane")
    @enable_banking_account.update!(raw_payload: { "uid" => "eb_uid_1", "name" => "JANE DOE" })

    tx = {
      entry_reference: "ref_holder_name_partial_match",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "8.00", currency: "EUR" },
      creditor: { name: "" },
      bank_transaction_code: nil,
      credit_debit_indicator: "DBIT",
      remittance_information: [ "Jane Doe" ],
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process

    assert_nil @account.entries.find_by!(external_id: "enable_banking_ref_holder_name_partial_match").transaction.merchant
  end

  test "reads the holder from a debtor given as a plain string" do
    @family.merchants.create!(name: "Jane Elizabeth Doe")
    @family.merchants.create!(name: "Example Shop")

    name = build_name_with_family(
      credit_debit_indicator: "DBIT",
      debtor: "JANE ELIZABETH DOE",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "EXAMPLE SHOP 1000 CITY Card payment JANE ELIZABETH DOE" ]
    )

    assert_equal "Example Shop", name
  end

  test "matches known merchants regardless of retailer chain" do
    %w[Bipa Spar Hofer Lidl Penny].each do |chain_name|
      @family.merchants.create!(name: chain_name)
    end

    [
      [ "bipa", "BIPA DANKT 0001234", "Bipa" ],
      [ "spar", "SPAR DANKT 0005678", "Spar" ],
      [ "hofer", "HOFER DANKT 0009876", "Hofer" ],
      [ "lidl", "LIDL DANKT 0004321", "Lidl" ],
      [ "penny", "DANKE 0009999 PENNY", "Penny" ]
    ].each do |ref_suffix, raw_line, expected_name|
      tx = {
        entry_reference: "ref_known_#{ref_suffix}",
        transaction_id: nil,
        booking_date: Date.current.to_s,
        transaction_amount: { amount: "12.34", currency: "EUR" },
        creditor: { name: "" },
        bank_transaction_code: nil,
        credit_debit_indicator: "DBIT",
        remittance_information: [
          "POS          12,34 AT  D6   01.01. 09:00",
          raw_line
        ],
        status: "BOOK"
      }

      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
      entry = @account.entries.find_by!(external_id: "enable_banking_ref_known_#{ref_suffix}")

      assert_equal expected_name, entry.name, "expected #{raw_line.inspect} to resolve to #{expected_name.inspect}"
    end
  end

  # --- identifiers assigned after the fact ---

  def identifierless_transaction(amount: "12.34", payee: "ACME 0001234", booking_date: Date.current)
    {
      transaction_id: nil,
      entry_reference: nil,
      booking_date: booking_date.to_s,
      transaction_amount: { amount: amount, currency: "EUR" },
      creditor: { name: "" },
      bank_transaction_code: nil,
      credit_debit_indicator: "DBIT",
      remittance_information: [ payee ],
      status: "BOOK"
    }
  end

  test "a transaction that later gains an identifier claims its own earlier row instead of importing twice" do
    raw = identifierless_transaction
    content_id = EnableBankingEntry::Processor.compute_external_id(raw)

    EnableBankingEntry::Processor.new(raw, enable_banking_account: @enable_banking_account).process
    assert @account.entries.exists?(external_id: content_id)
    before = @account.entries.count

    settled = raw.merge(entry_reference: "2026-01-01.1")
    settled_id = EnableBankingEntry::Processor.compute_external_id(settled)
    EnableBankingEntry::Processor.new(settled, enable_banking_account: @enable_banking_account).process

    assert_equal before, @account.entries.count, "the settled row should not import a second time"
    assert @account.entries.exists?(external_id: settled_id)
    assert_not @account.entries.exists?(external_id: content_id)
  end

  test "the superseded identifier is recorded so the stale payload row is skipped" do
    raw = identifierless_transaction(amount: "23.45")
    content_id = EnableBankingEntry::Processor.compute_external_id(raw)

    EnableBankingEntry::Processor.new(raw, enable_banking_account: @enable_banking_account).process

    settled = raw.merge(entry_reference: "2026-01-01.2")
    EnableBankingEntry::Processor.new(settled, enable_banking_account: @enable_banking_account).process

    entry = @account.entries.find_by!(external_id: EnableBankingEntry::Processor.compute_external_id(settled))
    recorded = Array(entry.transaction.extra[EnableBankingEntry::Processor::SUPERSEDED_IDS_KEY])
    assert_includes recorded, content_id
  end

  test "claiming a predecessor does not freeze the booking date against later corrections" do
    # auto_claimed_pending_ids would: Account::ProviderImportAdapter#import_transaction
    # keeps the stored date on any row carrying that key, forever. These are BOOK
    # rows whose date the ASPSP may still correct, so the claim must not set it.
    booked_on = Date.current - 3
    raw = identifierless_transaction(amount: "45.67", booking_date: booked_on)

    EnableBankingEntry::Processor.new(raw, enable_banking_account: @enable_banking_account).process

    settled = raw.merge(entry_reference: "2026-01-01.5")
    EnableBankingEntry::Processor.new(settled, enable_banking_account: @enable_banking_account).process

    entry = @account.entries.find_by!(external_id: EnableBankingEntry::Processor.compute_external_id(settled))
    assert_equal booked_on, entry.date

    corrected_on = booked_on + 1
    EnableBankingEntry::Processor.new(settled.merge(booking_date: corrected_on.to_s),
                                      enable_banking_account: @enable_banking_account).process

    assert_equal corrected_on, entry.reload.date, "a corrected booking date must still be applied"
  end

  test "an ASPSP identifier that looks synthesised still claims its predecessor" do
    raw = identifierless_transaction(amount: "56.78")
    content_id = EnableBankingEntry::Processor.compute_external_id(raw)

    EnableBankingEntry::Processor.new(raw, enable_banking_account: @enable_banking_account).process
    before = @account.entries.count

    # compute_external_id renders this as "enable_banking_content_..." even though
    # the ASPSP did supply an identifier, so a prefix check would misread it.
    settled = raw.merge(transaction_id: "content_0a1b2c3d")
    EnableBankingEntry::Processor.new(settled, enable_banking_account: @enable_banking_account).process

    assert_equal before, @account.entries.count
    assert_not @account.entries.exists?(external_id: content_id)
    assert @account.entries.exists?(external_id: EnableBankingEntry::Processor.compute_external_id(settled))
  end

  test "a predecessor already claimed elsewhere is not taken over" do
    raw = identifierless_transaction(amount: "67.89")
    content_id = EnableBankingEntry::Processor.compute_external_id(raw)

    EnableBankingEntry::Processor.new(raw, enable_banking_account: @enable_banking_account).process
    predecessor = @account.entries.find_by!(external_id: content_id)

    # Another sync of the same item claimed the row first. The set handed to this
    # processor still lists the content id, which is what a concurrent run would
    # see, so the claim is attempted and must decline.
    predecessor.update_column(:external_id, "enable_banking_claimed_elsewhere.1")

    settled = raw.merge(entry_reference: "2026-01-01.6")
    EnableBankingEntry::Processor.new(settled,
                                      enable_banking_account: @enable_banking_account,
                                      identifierless_external_ids: Set[content_id]).process

    assert_equal "enable_banking_claimed_elsewhere.1", predecessor.reload.external_id,
                 "the earlier claim must stand"
    assert @account.entries.exists?(external_id: EnableBankingEntry::Processor.compute_external_id(settled))
  end

  test "only one settled row claims the predecessor, so identical charges stay apart" do
    raw = identifierless_transaction(amount: "34.56")

    EnableBankingEntry::Processor.new(raw, enable_banking_account: @enable_banking_account).process
    before = @account.entries.count

    # Two settled rows with identical content and different identifiers: one real
    # movement was already stored, the other is a genuinely separate charge.
    first = raw.merge(entry_reference: "2026-01-01.3")
    second = raw.merge(entry_reference: "2026-01-01.4")
    EnableBankingEntry::Processor.new(first, enable_banking_account: @enable_banking_account).process
    EnableBankingEntry::Processor.new(second, enable_banking_account: @enable_banking_account).process

    assert_equal before + 1, @account.entries.count,
                 "the first settled row claims the predecessor, the second imports on its own"
  end

  test "a pending incoming payload does not claim an identifierless BOOK predecessor" do
    raw = identifierless_transaction(amount: "45.67")
    content_id = EnableBankingEntry::Processor.compute_external_id(raw)

    EnableBankingEntry::Processor.new(raw, enable_banking_account: @enable_banking_account).process
    before = @account.entries.count

    # Carries a real identifier, same content, but is itself still pending --
    # Enable Banking's own pending->booked reconciliation owns this transition,
    # not this claim mechanism.
    pending_settled = raw.merge(entry_reference: "2026-01-01.7", _pending: true)
    EnableBankingEntry::Processor.new(pending_settled, enable_banking_account: @enable_banking_account).process

    assert_equal before + 1, @account.entries.count,
                 "a pending payload must not re-key the BOOK predecessor"
    assert @account.entries.exists?(external_id: content_id),
           "the original BOOK row must be untouched"
  end

  test "a pending identifierless row is not offered as a claimable predecessor by THIS mechanism" do
    pending_raw = identifierless_transaction(amount: "56.78").merge(_pending: true)
    content_id = EnableBankingEntry::Processor.compute_external_id(pending_raw)

    EnableBankingEntry::Processor.new(pending_raw, enable_banking_account: @enable_banking_account).process
    predecessor = @account.entries.find_by!(external_id: content_id)

    settled = pending_raw.merge(entry_reference: "2026-01-01.8", _pending: false)
    settled_id = EnableBankingEntry::Processor.compute_external_id(settled)
    EnableBankingEntry::Processor.new(settled, enable_banking_account: @enable_banking_account).process

    # Enable Banking's own pending->booked reconciliation (ProviderImportAdapter's
    # amount/date pending_match, not claim_identifierless_predecessor!) is free to
    # claim this same row -- that is the intended outcome, and the whole point of
    # excluding pending rows from identifierless_external_ids_for is to let that
    # more conservative, purpose-built path own this transition instead of this
    # one. What matters here is which mechanism did the claiming, not whether a
    # claim happened at all.
    predecessor.reload
    assert_equal settled_id, predecessor.external_id,
                 "the existing pending->booked reconciliation should still settle this row"
    assert_not predecessor.transaction.pending?,
               "settling should have cleared the pending flag, same as any ordinary pending transaction"
  end

  # --- payment wallet prefixes ---

  test "a payment wallet prefix does not claim the transaction for the wallet's merchant" do
    @family.merchants.create!(name: "Apple")
    @family.merchants.create!(name: "Acme")

    tx = {
      entry_reference: "ref_wallet_prefix",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "17.95", currency: "EUR" },
      creditor: { name: "" },
      bank_transaction_code: nil,
      credit_debit_indicator: "DBIT",
      remittance_information: [ "Apple pay: ACME 0001234" ],
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_wallet_prefix")

    assert_equal "Acme", entry.name
    assert_equal "Acme", entry.transaction.merchant&.name
    # The wallet is still recorded: notes read remittance_information directly.
    assert_includes entry.notes, "Apple pay:"
  end

  test "a purchase from the wallet brand itself still resolves to that brand" do
    @family.merchants.create!(name: "Apple")

    tx = {
      entry_reference: "ref_wallet_own_brand",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "0.99", currency: "EUR" },
      creditor: { name: "" },
      bank_transaction_code: nil,
      credit_debit_indicator: "DBIT",
      remittance_information: [ "Apple pay: APPLE 0001234" ],
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_wallet_own_brand")

    assert_equal "Apple", entry.name
    assert_equal "Apple", entry.transaction.merchant&.name
  end

  test "strips every supported wallet prefix before matching a known merchant" do
    %w[Apple Google Samsung Acme].each { |merchant_name| @family.merchants.create!(name: merchant_name) }

    [ "Apple pay: ACME 0001234", "Google pay: ACME 0001234", "Samsung pay: ACME 0001234" ].each do |raw_line|
      name = build_name_with_family(
        credit_debit_indicator: "DBIT",
        creditor: { name: "" },
        bank_transaction_code: nil,
        remittance_information: [ raw_line ]
      )

      assert_equal "Acme", name, "expected #{raw_line.inspect} to resolve to \"Acme\""
    end
  end

  test "does not match a known merchant name shorter than the minimum match length" do
    @family.merchants.create!(name: "IT")

    name = build_name_with_family(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "NAME IT 1234" ]
    )

    # No known merchant match attempted ("IT" is below MIN_KNOWN_MERCHANT_MATCH_LENGTH),
    # so the line passes through unchanged.
    assert_equal "NAME IT 1234", name
  end

  test "prefers the longest matching known merchant name when multiple match" do
    @family.merchants.create!(name: "Billa")
    @family.merchants.create!(name: "Billa Corso")

    name = build_name_with_family(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "Billa Corso 0001234" ]
    )

    assert_equal "Billa Corso", name
  end

  test "escapes regex metacharacters in a known merchant name so matching never raises" do
    @family.merchants.create!(name: "A+B (Café)")

    name = build_name_with_family(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "A+B (Café) 0001234" ]
    )

    assert_equal "A+B (Café)", name
  end

  test "stores exchange_rate in extra when present" do
    tx = {
      entry_reference: "ref_fx",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "100.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      exchange_rate: {
        unit_currency: "USD",
        exchange_rate: "1.0821",
        rate_type: "SPOT",
        instructed_amount: { amount: "108.21", currency: "USD" }
      },
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_fx")
    eb_extra = entry.transaction&.extra&.dig("enable_banking")
    assert_equal "1.0821", eb_extra["fx_rate"]
    assert_equal "USD", eb_extra["fx_unit_currency"]
    assert_equal "108.21", eb_extra["fx_instructed_amount"]
  end

  test "stores merchant_category_code in extra when present" do
    tx = {
      entry_reference: "ref_mcc",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "25.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      merchant_category_code: "5411",
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_mcc")
    eb_extra = entry.transaction&.extra&.dig("enable_banking")
    assert_equal "5411", eb_extra["merchant_category_code"]
  end

  test "stores pending true in extra for PDNG-tagged transactions" do
    tx = {
      entry_reference: "ref_pdng",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "15.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      status: "PDNG",
      _pending: true
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_pdng")
    eb_extra = entry.transaction&.extra&.dig("enable_banking")
    assert_equal true, eb_extra["pending"]
  end

  # --- unidentified_hold? unit tests ---

  test "unidentified_hold? returns true when counterparty is absent and remittance has masked card descriptor" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: "2026-08-01",
      transaction_amount: { amount: "26.57", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879 003015315475" ],
      status: "BOOK"
    }
    assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "unidentified_hold? returns false when remittance lacks masked card descriptor" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: "2026-08-01",
      transaction_amount: { amount: "26.57", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "Arbitrary transfer" ],
      status: "BOOK"
    }
    assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "unidentified_hold? returns true when creditor has empty or blank name and remittance has masked card descriptor" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx)

    tx2 = {
      entry_reference: nil,
      transaction_id: nil,
      credit_debit_indicator: "DBIT",
      creditor: { name: nil },
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx2)
  end

  test "unidentified_hold? returns false when transaction_id is present" do
    tx = {
      entry_reference: nil,
      transaction_id: "txn_123",
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "unidentified_hold? returns false when entry_reference is present" do
    tx = {
      entry_reference: "ref_123",
      transaction_id: nil,
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "unidentified_hold? returns false when creditor name is present" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      credit_debit_indicator: "DBIT",
      creditor: { name: "Kaufland" },
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "unidentified_hold? returns false when creditor_name string is present" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      credit_debit_indicator: "DBIT",
      creditor_name: "Kaufland",
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "unidentified_hold? returns false for incoming CRDT when debtor is present" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      credit_debit_indicator: "CRDT",
      creditor: nil,
      debtor: { name: "Alice" },
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal false, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "unidentified_hold? returns true for incoming CRDT when debtor is absent and remittance has masked card descriptor" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      credit_debit_indicator: "CRDT",
      creditor: nil,
      debtor: nil,
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal true, EnableBankingEntry::Processor.unidentified_hold?(tx)
  end

  test "pending_payload? returns true for an unidentified hold" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879" ]
    }
    assert_equal true, EnableBankingEntry::Processor.pending_payload?(tx)
  end

  test "stores pending true in extra for unidentified holds" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "26.57", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "5168XXXXXXXX1234" ],
      status: "BOOK"
    }

    assert_difference "@account.entries.count", 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    content_id = EnableBankingEntry::Processor.compute_external_id(tx)
    entry = @account.entries.find_by!(external_id: content_id)
    eb_extra = entry.transaction&.extra&.dig("enable_banking")
    assert_equal true, eb_extra["pending"]
    assert entry.transaction.pending?
  end

  test "normalizes CRDT amount to positive (outflow) and name to Card Authorization Hold for masked card holds" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "14.97", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879 003015315475" ],
      status: "BOOK"
    }

    processor = EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account)
    entry = processor.process

    assert_not_nil entry
    assert_equal BigDecimal("14.97"), entry.amount, "Must be positive outflow in Sure convention"
    assert_equal "Card Authorization Hold", entry.name
    assert_nil entry.transaction.merchant
    assert_equal "474836xxxxxx6879 003015315475", entry.notes
    assert entry.transaction.pending?
  end

  test "does not invert CRDT amount for legitimate incoming transfer without card descriptor" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "50.00", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      creditor: nil,
      debtor: nil,
      remittance_information: [ "Gift from grandma" ],
      status: "BOOK"
    }

    processor = EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account)
    entry = processor.process

    assert_not_nil entry
    assert_equal BigDecimal("-50.00"), entry.amount, "Must remain negative inflow in Sure convention"
    assert_not_equal "Card Authorization Hold", entry.name
  end

  test "masked_card_descriptor? detects masked card numbers in remittance or bank transaction code" do
    assert EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "474836xxxxxx6879 003015315475" ])
    assert EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: "474836XXXXXX6879")
    assert EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "474836******6879" ])
    assert EnableBankingEntry::Processor.masked_card_descriptor?(bank_transaction_code: { description: "474836xxxxxx6879" })

    assert_not EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "Supermarket" ])
    assert_not EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: [ "Salary" ])
    assert_not EnableBankingEntry::Processor.masked_card_descriptor?(remittance_information: nil)
    assert_not EnableBankingEntry::Processor.masked_card_descriptor?(
      remittance_information: [ "Amazon.com", "474836xxxxxx6879 003015315475" ]
    )
    assert_not EnableBankingEntry::Processor.masked_card_descriptor?(
      remittance_information: [ "474836xxxxxx6879 003015315475", "Amazon.com" ]
    )
    # Technical terminal lines are ignored when finding descriptive remittance lines
    assert EnableBankingEntry::Processor.masked_card_descriptor?(
      remittance_information: [ "474836xxxxxx6879 003015315475", "POS   45,13 AT  D6   31.07. 10:27" ]
    )
    # Masked bank transaction code does not override legitimate remittance merchant
    assert_not EnableBankingEntry::Processor.masked_card_descriptor?(
      remittance_information: [ "Amazon.com" ],
      bank_transaction_code: { description: "474836xxxxxx6879" }
    )
  end

  test "does not treat multi-line remittance with legitimate payee and card PAN as unidentified hold" do
    # When payee matches a known merchant, preserves payee name and associates known merchant
    tx_known = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "29.99", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "Amazon.com", "474836xxxxxx6879 003015315475" ],
      status: "BOOK"
    }

    entry_known = EnableBankingEntry::Processor.new(tx_known, enable_banking_account: @enable_banking_account).process

    assert_not_nil entry_known
    assert_equal BigDecimal("29.99"), entry_known.amount
    assert_equal "Amazon", entry_known.name
    assert_equal "Amazon", entry_known.transaction.merchant&.name
    assert_not entry_known.transaction.pending?

    # When payee is not an existing known merchant, preserves remittance text as entry name
    tx_unknown = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "15.50", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "Acme Store", "474836xxxxxx6879 003015315475" ],
      status: "BOOK"
    }

    entry_unknown = EnableBankingEntry::Processor.new(tx_unknown, enable_banking_account: @enable_banking_account).process

    assert_not_nil entry_unknown
    assert_equal BigDecimal("15.50"), entry_unknown.amount
    assert_equal "Acme Store", entry_unknown.name
    assert_not entry_unknown.transaction.pending?
  end

  test "captures warning DebugLogEntry when processing unidentified card hold on first import only" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "14.97", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879 003015315475" ],
      status: "BOOK"
    }

    assert_difference -> { DebugLogEntry.count }, 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    log_entry = DebugLogEntry.last
    assert_equal "provider_sync", log_entry.category
    assert_equal "warn", log_entry.level
    assert_equal "enable_banking", log_entry.provider_key
    assert_equal @account, log_entry.account
    assert_equal @account.family, log_entry.family
    assert_equal @enable_banking_account.account_provider, log_entry.account_provider
    assert_equal CardAuthorizationHold::HOLD_DIAGNOSTIC_MESSAGE, log_entry.message
    assert_equal true, log_entry.metadata["sign_inverted"]
    assert_equal "14.97", log_entry.metadata["raw_amount"]
    assert_equal "CRDT", log_entry.metadata["credit_debit_indicator"]

    # Re-processing the same hold on subsequent sync does not write duplicate DebugLogEntry
    assert_no_difference -> { DebugLogEntry.count } do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end
  end

  test "captures warning DebugLogEntry with sign_inverted false for DBIT unidentified hold" do
    tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "20.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879 003015315475" ],
      status: "BOOK"
    }

    assert_difference -> { DebugLogEntry.count }, 1 do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end

    log_entry = DebugLogEntry.last
    assert_equal false, log_entry.metadata["sign_inverted"]
    assert_equal "DBIT", log_entry.metadata["credit_debit_indicator"]
    assert_equal "20.00", log_entry.metadata["raw_amount"]
  end

  test "does not capture DebugLogEntry for regular transactions" do
    tx = {
      entry_reference: "ref_regular",
      transaction_id: "tx_regular",
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "14.97", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: { name: "Regular Store" },
      status: "BOOK"
    }

    assert_no_difference -> { DebugLogEntry.count } do
      EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    end
  end

  test "reconciles and claims unfinalized card hold when settled booked transaction arrives" do
    # 1. First sync: unfinalized card hold arrives with status BOOK, CRDT, no counterparty, masked remittance
    hold_tx = {
      entry_reference: nil,
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "14.97", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      creditor: nil,
      remittance_information: [ "474836xxxxxx6879 003015315475" ],
      status: "BOOK"
    }

    hold_entry = EnableBankingEntry::Processor.new(hold_tx, enable_banking_account: @enable_banking_account).process
    assert_not_nil hold_entry
    assert_equal BigDecimal("14.97"), hold_entry.amount
    assert_equal "Card Authorization Hold", hold_entry.name
    assert hold_entry.transaction.pending?

    # 2. Later sync: settled booked transaction arrives with real creditor, DBIT, and identifiers
    settled_tx = {
      entry_reference: "ref_settled_999",
      transaction_id: "txn_settled_999",
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "14.97", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      creditor: { name: "Billa" },
      remittance_information: [ "BILLA DANKT 0007114" ],
      status: "BOOK"
    }

    settled_entry = EnableBankingEntry::Processor.new(settled_tx, enable_banking_account: @enable_banking_account).process
    assert_not_nil settled_entry

    # Should have claimed the pending hold entry instead of creating a duplicate
    assert_equal hold_entry.id, settled_entry.id, "Settled transaction must claim the pending hold row"
    assert_equal "enable_banking_txn_settled_999", settled_entry.external_id
    assert_not settled_entry.transaction.pending?, "Pending flag must be cleared upon settlement"
    assert_equal 1, @account.entries.where(source: "enable_banking").count
  end

  test "does not add enable_banking extra key when no extra data present" do
    tx = {
      entry_reference: "ref_noextra",
      transaction_id: nil,
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "5.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      status: "BOOK"
    }

    EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process
    entry = @account.entries.find_by!(external_id: "enable_banking_ref_noextra")
    assert_nil entry.transaction&.extra&.dig("enable_banking")
  end

  def build_processor(data)
    # A minimal stand-in that responds to current_account (real EnableBankingAccount
    # always does) so `account`/`known_merchant_names` resolve safely to nil/[] instead
    # of raising -- these unit-level tests aren't wired to a real family, so they always
    # exercise the "no known merchant" fallback path.
    EnableBankingEntry::Processor.new(data, enable_banking_account: OpenStruct.new(current_account: nil))
  end

  def build_name(data)
    build_processor(data).send(:name)
  end

  # Unlike build_name/build_processor, wires up the real @enable_banking_account
  # (and thus the real @family) so known-merchant matching has something to match
  # against -- used by tests that create FamilyMerchant records via @family first.
  def build_name_with_family(data)
    EnableBankingEntry::Processor.new(data, enable_banking_account: @enable_banking_account).send(:name)
  end

  # An Enable Banking account linked to the investment fixture, for tests of
  # investment activity labels.
  def investment_enable_banking_account
    @investment_enable_banking_account ||= begin
      enable_banking_account = EnableBankingAccount.create!(
        enable_banking_item: @enable_banking_item,
        name: "Depot",
        uid: "eb_uid_investment",
        currency: "EUR"
      )
      AccountProvider.create!(account: accounts(:investment), provider: enable_banking_account)
      enable_banking_account
    end
  end

  test "skips technical card counterparty and falls back to remittance_information" do
    name = build_name(
      credit_debit_indicator: "CRDT",
      debtor_name: "CARD-1234",
      remittance_information: [ "ACME SHOP" ],
      bank_transaction_code: { description: "Card Purchase" }
    )

    assert_equal "ACME SHOP", name
  end

  test "combines the remittance merchant with a generic transaction type description" do
    # SEB sends no counterparty for card purchases; the merchant is only in the remittance
    name = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "RACKSTA KROG" ],
      bank_transaction_code: { description: "Card purchase" }
    )

    assert_equal "RACKSTA KROG - Card purchase", name
  end

  test "keeps payments of different types to the same payee apart" do
    direct_debit = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "TELIA SVERIGE" ],
      bank_transaction_code: { description: "Direct debit" }
    )
    card_purchase = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "TELIA SVERIGE" ],
      bank_transaction_code: { description: "Card purchase" }
    )

    assert_equal "TELIA SVERIGE - Direct debit", direct_debit
    assert_equal "TELIA SVERIGE - Card purchase", card_purchase
  end

  test "detects the investment activity label from the transaction type description" do
    tx = {
      transaction_id: "txn_dividend",
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "12.50", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      remittance_information: [ "ACME CORP" ],
      bank_transaction_code: { description: "Dividend" },
      status: "BOOK"
    }

    entry = EnableBankingEntry::Processor.new(tx, enable_banking_account: investment_enable_banking_account).process

    assert_equal "ACME CORP - Dividend", entry.name
    assert_equal "Dividend", entry.transaction.investment_activity_label
  end

  test "does not detect an investment activity label from the payee of a combined name" do
    tx = {
      transaction_id: "txn_fund_transfer",
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "100.00", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      remittance_information: [ "Dividend Growth Fund" ],
      bank_transaction_code: { description: "Credit transfer" },
      status: "BOOK"
    }

    entry = EnableBankingEntry::Processor.new(tx, enable_banking_account: investment_enable_banking_account).process

    assert_equal "Dividend Growth Fund - Credit transfer", entry.name
    assert_nil entry.transaction.investment_activity_label
  end

  test "still detects an investment activity label from a counterparty name" do
    tx = {
      transaction_id: "txn_counterparty_dividend",
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "8.00", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      debtor: { name: "Dividend payment ACME" },
      bank_transaction_code: { description: "Credit transfer" },
      status: "BOOK"
    }

    entry = EnableBankingEntry::Processor.new(tx, enable_banking_account: investment_enable_banking_account).process

    assert_equal "Dividend payment ACME", entry.name
    assert_equal "Dividend", entry.transaction.investment_activity_label
  end

  test "does not set an investment activity label on a non-investment account" do
    tx = {
      transaction_id: "txn_interest",
      booking_date: Date.current.to_s,
      transaction_amount: { amount: "3.10", currency: "EUR" },
      credit_debit_indicator: "CRDT",
      remittance_information: [ "SAVINGS BANK" ],
      bank_transaction_code: { description: "Interest" },
      status: "BOOK"
    }

    entry = EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process

    assert_equal "SAVINGS BANK - Interest", entry.name
    assert_nil entry.transaction.investment_activity_label
  end

  test "uses a later remittance line when the first one is only a reference" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "52220151204", "TELIA SVERIGE" ],
      bank_transaction_code: { description: "Direct debit" }
    )

    assert_equal "TELIA SVERIGE - Direct debit", name
  end

  test "keeps the transaction type description when the remittance is a spaced masked card number" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      transaction_id: "txn_spaced_masked_pan",
      remittance_information: [ "474836 XXXXXX 6879" ],
      bank_transaction_code: { description: "Card purchase" }
    )

    assert_equal "Card purchase", name
  end

  test "keeps the transaction type description when the remittance is a labelled reference" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "Reference 0394676" ],
      bank_transaction_code: { description: "Credit transfer" }
    )

    assert_equal "Credit transfer", name
  end

  test "skips a labelled reference and uses the payee on a later line" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "Faktura nr 12345", "TELIA SVERIGE" ],
      bank_transaction_code: { description: "Direct debit" }
    )

    assert_equal "TELIA SVERIGE - Direct debit", name
  end

  test "keeps a short known merchant name over a later descriptive line" do
    @family.merchants.create!(name: "H&M")

    name = build_name_with_family(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "H&M", "LONDON" ]
    )

    assert_equal "H&M", name
  end

  test "does not treat a merchant name starting with a reference keyword as a reference" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "REFILL STATION 2" ],
      bank_transaction_code: { description: "Card purchase" }
    )

    assert_equal "REFILL STATION 2 - Card purchase", name
  end

  test "uses the descriptive remittance alone when there is no transaction type description" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "RACKSTA KROG" ],
      bank_transaction_code: { code: "PMNT" }
    )

    assert_equal "RACKSTA KROG", name
  end

  test "keeps the transaction type description when the remittance is a masked card number" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      transaction_id: "txn_masked_pan",
      remittance_information: [ "474836xxxxxx6879" ],
      bank_transaction_code: { description: "Card purchase" }
    )

    assert_equal "Card purchase", name
  end

  test "keeps the transaction type description when the remittance is only a reference" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      remittance_information: [ "52220151204 092408560500" ],
      bank_transaction_code: { description: "Credit transfer" }
    )

    assert_equal "Credit transfer", name
  end

  test "keeps the transaction type description when the remittance is the account holder" do
    name = build_name_with_family(
      credit_debit_indicator: "CRDT",
      creditor: { name: "JANE DOE" },
      remittance_information: [ "Jane Doe" ],
      bank_transaction_code: { description: "Transfer" }
    )

    assert_equal "Transfer", name
  end

  test "uses counterparty when it is human readable" do
    name = build_name(
      credit_debit_indicator: "CRDT",
      debtor_name: "ACME SHOP",
      remittance_information: [ "Receipt #42" ],
      bank_transaction_code: { description: "Transfer" }
    )

    assert_equal "ACME SHOP", name
  end

  test "falls back to top-level counterparty name when nested name is blank" do
    processor = build_processor(
      credit_debit_indicator: "CRDT",
      debtor: { name: "" },
      debtor_name: "ACME SHOP"
    )

    assert_equal "ACME SHOP", processor.send(:name)

    merchant = stub(id: 789)
    import_adapter = mock("import_adapter")
    import_adapter.expects(:find_or_create_merchant).with(
      provider_merchant_id: "enable_banking_merchant_c0b09f27a4375bb8d8d477ed552a9aa1",
      name: "ACME SHOP",
      source: "enable_banking"
    ).returns(merchant)

    processor.stubs(:import_adapter).returns(import_adapter)

    assert_equal merchant, processor.send(:merchant)
  end

  test "builds merchant from remittance when counterparty is technical card id" do
    processor = build_processor(
      credit_debit_indicator: "CRDT",
      debtor_name: "CARD-1234",
      remittance_information: [ "ACME SHOP" ],
      bank_transaction_code: { description: "Card Purchase" }
    )

    merchant = stub(id: 123)
    import_adapter = mock("import_adapter")
    import_adapter.expects(:find_or_create_merchant).with(
      provider_merchant_id: "enable_banking_merchant_c0b09f27a4375bb8d8d477ed552a9aa1",
      name: "ACME SHOP",
      source: "enable_banking"
    ).returns(merchant)

    processor.stubs(:import_adapter).returns(import_adapter)

    assert_equal merchant, processor.send(:merchant)
  end

  test "uses remittance fallback for debit technical card counterparty" do
    processor = build_processor(
      credit_debit_indicator: "DBIT",
      creditor_name: "CARD-1234",
      remittance_information: [ "ACME SHOP" ],
      bank_transaction_code: { description: "Card Purchase" }
    )

    assert_equal "ACME SHOP", processor.send(:name)

    merchant = stub(id: 321)
    import_adapter = mock("import_adapter")
    import_adapter.expects(:find_or_create_merchant).with(
      provider_merchant_id: "enable_banking_merchant_c0b09f27a4375bb8d8d477ed552a9aa1",
      name: "ACME SHOP",
      source: "enable_banking"
    ).returns(merchant)

    processor.stubs(:import_adapter).returns(import_adapter)

    assert_equal merchant, processor.send(:merchant)
  end

  test "truncates remittance-derived merchant names before persisting" do
    long_name = "A" * 150
    truncated_name = "A" * 100
    processor = build_processor(
      credit_debit_indicator: "CRDT",
      debtor_name: "CARD-1234",
      remittance_information: [ long_name ]
    )

    merchant = stub(id: 654)
    import_adapter = mock("import_adapter")
    import_adapter.expects(:find_or_create_merchant).with(
      provider_merchant_id: "enable_banking_merchant_#{Digest::MD5.hexdigest(truncated_name.downcase)}",
      name: truncated_name,
      source: "enable_banking"
    ).returns(merchant)

    processor.stubs(:import_adapter).returns(import_adapter)

    assert_equal merchant, processor.send(:merchant)
  end

  test "uses string remittance fallback for technical card counterparty" do
    processor = build_processor(
      credit_debit_indicator: "CRDT",
      debtor_name: "CARD-1234",
      remittance_information: "ACME SHOP"
    )

    assert_equal "ACME SHOP", processor.send(:name)

    merchant = stub(id: 456)
    import_adapter = mock("import_adapter")
    import_adapter.expects(:find_or_create_merchant).with(
      provider_merchant_id: "enable_banking_merchant_c0b09f27a4375bb8d8d477ed552a9aa1",
      name: "ACME SHOP",
      source: "enable_banking"
    ).returns(merchant)

    processor.stubs(:import_adapter).returns(import_adapter)

    assert_equal merchant, processor.send(:merchant)
  end

  test "does not build merchant from remittance when counterparty is blank" do
    processor = build_processor(
      credit_debit_indicator: "CRDT",
      debtor_name: nil,
      remittance_information: [ "Invoice 12345" ]
    )

    assert_nil processor.send(:merchant)
  end

  # --- technical remittance line skip (issue #2935) ---

  test "skips generic POS terminal line and uses real merchant from remittance_information" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [
        "POS          45,13 AT  D6   31.07. 10:27",
        "BILLA DANKT 0007114"
      ]
    )

    assert_equal "BILLA DANKT 0007114", name
  end

  test "skips generic ATM terminal line and uses real merchant from remittance_information" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [
        "ATM          50,00 AT  D6   31.07. 10:27",
        "SPARKASSE EISENSTADT 7000"
      ]
    )

    assert_equal "SPARKASSE EISENSTADT 7000", name
  end

  test "does not treat a POS/ATM-prefixed line as technical when it lacks a trailing date+time (merchant embedded in the same line)" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [
        "POS 45,13 BILLA DANKT 0007114",
        "Reference 0394676"
      ]
    )

    assert_equal "POS 45,13 BILLA DANKT 0007114", name
  end

  test "does not treat a legitimate line as technical just because it ends with a date+time stamp" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [
        "Invoice paid 31.07. 10:27",
        "Reference 0394676"
      ]
    )

    assert_equal "Invoice paid 31.07. 10:27", name
  end

  test "strips SumUp payment processor prefix from the merchant line" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [
        "POS         130,00 AT  D6   21.07. 14:20",
        "SUMUP  *HERR DR. EISENSTADT 7000"
      ]
    )

    assert_equal "HERR DR. EISENSTADT 7000", name
  end

  test "falls back to the technical line when remittance_information has no descriptive line" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "POS          45,13 AT  D6   31.07. 10:27" ]
    )

    assert_equal "POS          45,13 AT  D6   31.07. 10:27", name
  end

  test "does not treat a merchant-like line starting with POS/ATM as technical" do
    name = build_name(
      credit_debit_indicator: "DBIT",
      creditor: { name: "" },
      bank_transaction_code: nil,
      remittance_information: [ "POS Café Wien" ]
    )

    assert_equal "POS Café Wien", name
  end

  test "converts unix timestamp date using family timezone not UTC" do
    # 2025-07-14 23:30:00 UTC == 2025-07-15 01:30:00 CEST
    @family.update!(timezone: "Europe/Berlin")

    tx = {
      entry_reference: "tz_ref",
      transaction_id: nil,
      booking_date: 1752535800, # 2025-07-14 23:30:00 UTC
      transaction_amount: { amount: "10.00", currency: "EUR" },
      creditor: { name: "Late Night Shop" },
      credit_debit_indicator: "DBIT",
      remittance_information: [ "After midnight" ],
      status: "BOOK"
    }

    result = EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process

    assert_not_nil result
    assert_equal Date.new(2025, 7, 15), result.date
  end

  test "external_ids_for leaves rows without a shared transaction_id on compute_external_id" do
    rows = [
      { entry_reference: "ref-1", booking_date: "2026-03-05", transaction_amount: { amount: "1.00", currency: "EUR" } },
      { booking_date: "2026-03-05", transaction_amount: { amount: "2.00", currency: "EUR" }, remittance_information: [ "X" ] },
      { transaction_id: "tid-y", entry_reference: "ref-2", booking_date: "2026-03-05", transaction_amount: { amount: "3.00", currency: "EUR" } },
      { transaction_id: "tid-z", booking_date: "2026-03-05", transaction_amount: { amount: "4.00", currency: "EUR" } },
      { transaction_id: "tid-z", booking_date: "2026-03-05", transaction_amount: { amount: "5.00", currency: "EUR" } }
    ]

    assert_equal rows.map { |r| EnableBankingEntry::Processor.compute_external_id(r) },
                 EnableBankingEntry::Processor.external_ids_for(rows)
  end
end