Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
43.8 KB
Raw Blame
require "test_helper"

class EnableBankingAccount::Transactions::ProcessorTest < ActiveSupport::TestCase
  include EntriesTestHelper

  setup do
    @family = families(:dylan_family)
    @account = accounts(:depository)

    @enable_banking_item = EnableBankingItem.create!(
      family:              @family,
      name:                "Test EB Item",
      country_code:        "FR",
      application_id:      "app_id",
      client_certificate:  "cert"
    )
    @enable_banking_account = EnableBankingAccount.create!(
      enable_banking_item: @enable_banking_item,
      name:                "Compte courant",
      uid:                 "uid_txn_proc_test",
      currency:            "EUR",
      current_balance:     1000.00
    )
    AccountProvider.create!(account: @account, provider: @enable_banking_account)
  end

  # Minimal raw transaction payload hash matching the shape EnableBankingEntry::Processor expects
  def raw_pending_transaction(transaction_id:)
    {
      transaction_id:       transaction_id,
      value_date:           3.days.ago.to_date.to_s,
      transaction_amount:   { amount: "25.00", currency: "EUR" },
      credit_debit_indicator: "DBIT",
      _pending:             true
    }
  end

  # Same movement before and after the ASPSP assigns it an entry_reference. The
  # stored payload is never pruned, so both rows reach the processor in one batch.
  def raw_identifierless_transaction(amount: "31.00")
    {
      transaction_id:         nil,
      entry_reference:        nil,
      booking_date:           2.days.ago.to_date.to_s,
      transaction_amount:     { amount: amount, currency: "EUR" },
      creditor:               { name: "" },
      credit_debit_indicator: "DBIT",
      remittance_information: [ "ACME 0009876" ],
      status:                 "BOOK"
    }
  end

  test "stored rows before sync_start_date are kept raw but not imported" do
    @enable_banking_item.update!(sync_start_date: 10.days.ago.to_date)
    old_row = raw_identifierless_transaction(amount: "40.00").merge(transaction_id: "old", booking_date: 30.days.ago.to_date.to_s)
    new_row = raw_identifierless_transaction(amount: "41.00").merge(transaction_id: "new")

    @enable_banking_account.update!(raw_transactions_payload: [ old_row, new_row ])
    result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal 1, result[:skipped]
    assert_equal 1, @account.entries.where(source: "enable_banking").count
    assert @account.entries.exists?(external_id: EnableBankingEntry::Processor.compute_external_id(new_row))
  end

  test "a movement identified later in the same batch does not import twice" do
    identifierless = raw_identifierless_transaction
    settled = identifierless.merge(entry_reference: "2026-02-02.1")

    @enable_banking_account.update!(raw_transactions_payload: [ identifierless, settled ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal 1, @account.entries.where(source: "enable_banking").count
    assert @account.entries.exists?(external_id: EnableBankingEntry::Processor.compute_external_id(settled))
  end

  test "a stale identifierless row later in the same batch is skipped, not reimported" do
    identifierless = raw_identifierless_transaction(amount: "32.00")
    settled = identifierless.merge(entry_reference: "2026-02-02.2")

    # The identifierless row is already stored from an earlier sync.
    @enable_banking_account.update!(raw_transactions_payload: [ identifierless ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    assert_equal 1, @account.entries.where(source: "enable_banking").count

    # Now the settled row arrives ahead of the stale one it supersedes.
    @enable_banking_account.update!(raw_transactions_payload: [ settled, identifierless ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal 1, @account.entries.where(source: "enable_banking").count
    assert @account.entries.exists?(external_id: EnableBankingEntry::Processor.compute_external_id(settled))
  end

  test "a pending identifierless row earlier in the same batch is left to pending->booked reconciliation" do
    pending_raw = raw_identifierless_transaction(amount: "33.00").merge(status: "PDNG", _pending: true)
    settled = raw_identifierless_transaction(amount: "33.00").merge(entry_reference: "2026-02-02.3")

    @enable_banking_account.update!(raw_transactions_payload: [ pending_raw, settled ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    entries = @account.entries.where(source: "enable_banking")
    assert_equal 1, entries.count
    entry = entries.first
    assert_equal EnableBankingEntry::Processor.compute_external_id(settled), entry.external_id
    assert_not entry.transaction.pending?
    # The claim would have recorded the content hash it superseded; the adapter's
    # pending match does not. Which mechanism settled the row is the point here.
    assert_not entry.transaction.extra.to_h.key?("superseded_external_ids"),
               "the same-batch claim set must not offer a pending row as a predecessor"
  end

  test "does not re-import a pending transaction whose external_id was manually merged" do
    pending_ext_id = "enable_banking_PDNG_MERGED"

    # Simulate a previously-merged state: a posted transaction carries the pending's external_id
    # in its manual_merge metadata, which is how merge_with_duplicate! records the merge.
    posted_entry = create_transaction(
      account:     @account,
      name:        "Coffee Shop",
      date:        1.day.ago.to_date,
      amount:      25,
      currency:    "EUR",
      external_id: "enable_banking_BOOK_SETTLED",
      source:      "enable_banking"
    )
    posted_entry.transaction.update!(
      extra: {
        "manual_merge" => {
          "merged_from_entry_id"    => SecureRandom.uuid,
          "merged_from_external_id" => pending_ext_id,
          "merged_at"               => Time.current.iso8601,
          "source"                  => "enable_banking"
        }
      }
    )
    posted_entry.mark_user_modified!

    # Raw payload contains the pending transaction that was already merged
    @enable_banking_account.update!(
      raw_transactions_payload: [
        raw_pending_transaction(transaction_id: "PDNG_MERGED")
      ]
    )

    assert_no_difference "@account.entries.count" do
      EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    end
  end

  test "imports a pending transaction that has NOT been merged" do
    @enable_banking_account.update!(
      raw_transactions_payload: [
        raw_pending_transaction(transaction_id: "PDNG_NEW_UNMERGED")
      ]
    )

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

  test "imports non-excluded transactions alongside excluded ones in the same batch" do
    pending_ext_id = "enable_banking_PDNG_SKIP_ME"

    posted_entry = create_transaction(
      account:     @account,
      name:        "Already Merged",
      date:        2.days.ago.to_date,
      amount:      15,
      currency:    "EUR",
      external_id: "enable_banking_BOOK_ALREADY",
      source:      "enable_banking"
    )
    posted_entry.transaction.update!(
      extra: {
        "manual_merge" => {
          "merged_from_external_id" => pending_ext_id,
          "merged_at"               => Time.current.iso8601,
          "source"                  => "enable_banking"
        }
      }
    )

    @enable_banking_account.update!(
      raw_transactions_payload: [
        raw_pending_transaction(transaction_id: "PDNG_SKIP_ME"),          # excluded
        raw_pending_transaction(transaction_id: "PDNG_BRAND_NEW_12345")   # should be imported
      ]
    )

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

  test "excludes all external_ids when multiple pending entries were merged into the same posted entry" do
    pending_ext_id_1 = "enable_banking_PDNG_MULTI_1"
    pending_ext_id_2 = "enable_banking_PDNG_MULTI_2"

    posted_entry = create_transaction(
      account:     @account,
      name:        "Multi Merge",
      date:        2.days.ago.to_date,
      amount:      30,
      currency:    "EUR",
      external_id: "enable_banking_BOOK_MULTI",
      source:      "enable_banking"
    )
    posted_entry.transaction.update!(
      extra: {
        "manual_merge" => [
          { "merged_from_external_id" => pending_ext_id_1, "merged_at" => 2.days.ago.iso8601, "source" => "enable_banking" },
          { "merged_from_external_id" => pending_ext_id_2, "merged_at" => 1.day.ago.iso8601,  "source" => "enable_banking" }
        ]
      }
    )

    @enable_banking_account.update!(
      raw_transactions_payload: [
        raw_pending_transaction(transaction_id: "PDNG_MULTI_1"),  # excluded
        raw_pending_transaction(transaction_id: "PDNG_MULTI_2"),  # excluded
        raw_pending_transaction(transaction_id: "PDNG_MULTI_NEW") # new — should import
      ]
    )

    result = nil
    assert_difference "@account.entries.count", 1 do
      result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    end
    assert_equal 2, result[:skipped]
    assert_equal 1, result[:imported]
  end

  test "imports id-less transaction using content fingerprint" do
    tx = {
      "booking_date" => Date.current.to_s,
      "transaction_amount" => { "amount" => "19.99", "currency" => "EUR" },
      "credit_debit_indicator" => "DBIT",
      "creditor" => { "name" => "Spotify" }
    }
    @enable_banking_account.update!(raw_transactions_payload: [ tx ])

    assert_difference "@account.entries.count", 1 do
      EnableBankingAccount::Transactions::Processor.new(@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 "id-less transaction does not appear in failed count" do
    tx = {
      "booking_date" => Date.current.to_s,
      "transaction_amount" => { "amount" => "5.00", "currency" => "EUR" },
      "credit_debit_indicator" => "CRDT",
      "debtor" => { "name" => "Employer" }
    }
    @enable_banking_account.update!(raw_transactions_payload: [ tx ])

    result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal 0, result[:failed]
  end

  test "an identifierless copy in the batch does not split a movement that settles a pending entry" do
    pending_entry = create_transaction(
      account:     @account,
      name:        "Card authorisation",
      date:        3.days.ago.to_date,
      amount:      25,
      currency:    "EUR",
      external_id: "enable_banking_B",
      source:      "enable_banking"
    )
    pending_entry.transaction.update!(extra: { "enable_banking" => { "pending" => true } })

    identifierless = raw_identifierless_transaction(amount: "25.00")
    identified = identifierless.merge(transaction_id: "T", entry_reference: "B")
    @enable_banking_account.update!(raw_transactions_payload: [ identifierless, identified ])

    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal [ "enable_banking_T" ], @account.entries.where(source: "enable_banking").pluck(:external_id)
  end

  test "an unrelated identifierless row of the same amount does not take a pending entry before its settling row" do
    pending_entry = create_transaction(
      account:     @account,
      name:        "Card authorisation",
      date:        3.days.ago.to_date,
      amount:      25,
      currency:    "EUR",
      external_id: "enable_banking_B",
      source:      "enable_banking"
    )
    pending_entry.transaction.update!(extra: { "enable_banking" => { "pending" => true } })

    unrelated = raw_identifierless_transaction(amount: "25.00").merge(remittance_information: [ "OTHER 0001234" ])
    identified = raw_identifierless_transaction(amount: "25.00").merge(transaction_id: "T", entry_reference: "B")
    @enable_banking_account.update!(raw_transactions_payload: [ unrelated, identified ])

    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal "enable_banking_T", pending_entry.reload.external_id
    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end

  test "a settling row whose content key raises fails on its own" do
    pending_entry = create_transaction(
      account:     @account,
      name:        "Card authorisation",
      date:        3.days.ago.to_date,
      amount:      25,
      currency:    "EUR",
      external_id: "enable_banking_B",
      source:      "enable_banking"
    )
    pending_entry.transaction.update!(extra: { "enable_banking" => { "pending" => true } })

    malformed = raw_identifierless_transaction.merge(transaction_id: "M", entry_reference: "B", transaction_amount: "25.00")
    booked = raw_identifierless_transaction(amount: "9.00").merge(transaction_id: "OK")
    @enable_banking_account.update!(raw_transactions_payload: [ malformed, booked ])

    result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal [ 0 ], result[:errors].map { |error| error[:index] }
    assert @account.entries.exists?(external_id: "enable_banking_OK", source: "enable_banking")
  end

  test "does not re-import a pending transaction whose external_id was auto-claimed" do
    # When a pending entry is automatically matched to a booked transaction by the
    # amount/date heuristic (find_pending_transaction), the old pending external_id
    # is stored in auto_claimed_pending_ids so subsequent syncs don't recreate it.
    pending_ext_id = "enable_banking_PDNG_AUTO_CLAIMED"

    booked_entry = create_transaction(
      account:     @account,
      name:        "Grocery Store",
      date:        1.day.ago.to_date,
      amount:      55,
      currency:    "EUR",
      external_id: "enable_banking_BOOK_SETTLED",
      source:      "enable_banking"
    )
    booked_entry.transaction.update!(
      extra: {
        "auto_claimed_pending_ids" => [ pending_ext_id ]
      }
    )

    @enable_banking_account.update!(
      raw_transactions_payload: [
        raw_pending_transaction(transaction_id: "PDNG_AUTO_CLAIMED")
      ]
    )

    assert_no_difference "@account.entries.count" do
      EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    end
  end

  test "does not re-import when both manual_merge and auto_claimed_pending_ids exclusions are present" do
    manually_merged_ext_id  = "enable_banking_PDNG_MANUAL"
    auto_claimed_ext_id     = "enable_banking_PDNG_AUTO"

    manual_entry = create_transaction(
      account:     @account,
      name:        "Manual Merge Entry",
      date:        2.days.ago.to_date,
      amount:      20,
      currency:    "EUR",
      external_id: "enable_banking_BOOK_MANUAL",
      source:      "enable_banking"
    )
    manual_entry.transaction.update!(
      extra: {
        "manual_merge" => {
          "merged_from_external_id" => manually_merged_ext_id,
          "merged_at"               => Time.current.iso8601,
          "source"                  => "enable_banking"
        }
      }
    )

    auto_entry = create_transaction(
      account:     @account,
      name:        "Auto Claimed Entry",
      date:        1.day.ago.to_date,
      amount:      30,
      currency:    "EUR",
      external_id: "enable_banking_BOOK_AUTO",
      source:      "enable_banking"
    )
    auto_entry.transaction.update!(
      extra: { "auto_claimed_pending_ids" => [ auto_claimed_ext_id ] }
    )

    @enable_banking_account.update!(
      raw_transactions_payload: [
        raw_pending_transaction(transaction_id: "PDNG_MANUAL"),         # excluded via manual_merge
        raw_pending_transaction(transaction_id: "PDNG_AUTO"),           # excluded via auto_claimed_pending_ids
        raw_pending_transaction(transaction_id: "PDNG_BRAND_NEW_XXXX")  # new — should import
      ]
    )

    result = nil
    assert_difference "@account.entries.count", 1 do
      result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    end
    assert_equal 2, result[:skipped]
    assert_equal 1, result[:imported]
  end

  test "handles empty raw_transactions_payload gracefully" do
    @enable_banking_account.update!(raw_transactions_payload: nil)

    result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal true, result[:success]
    assert_equal 0, result[:total]
  end

  test "reports excluded transactions as skipped, not imported or failed" do
    pending_ext_id = "enable_banking_PDNG_SKIP_STATS"

    posted_entry = create_transaction(
      account:     @account,
      name:        "Stats Test",
      date:        2.days.ago.to_date,
      amount:      50,
      currency:    "EUR",
      external_id: "enable_banking_BOOK_STATS",
      source:      "enable_banking"
    )
    posted_entry.transaction.update!(
      extra: { "manual_merge" => { "merged_from_external_id" => pending_ext_id } }
    )

    @enable_banking_account.update!(
      raw_transactions_payload: [
        raw_pending_transaction(transaction_id: "PDNG_SKIP_STATS")
      ]
    )

    result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal true, result[:success]
    assert_equal 1,    result[:skipped]
    assert_equal 0,    result[:imported]
    assert_equal 0,    result[:failed]
  end

  # transaction_id is not guaranteed unique; entry_reference tells the rows apart.
  def raw_shared_tid_transaction(entry_reference:, amount:)
    {
      transaction_id:         "tid-x",
      entry_reference:        entry_reference,
      booking_date:           2.days.ago.to_date.to_s,
      transaction_amount:     { amount: amount, currency: "EUR" },
      creditor:               { name: "Laundromat" },
      credit_debit_indicator: "DBIT",
      status:                 "BOOK"
    }
  end

  def sibling_id(entry_reference)
    "enable_banking_tid-x_#{Digest::MD5.hexdigest(entry_reference)}"
  end

  test "rows sharing a transaction_id with different entry_references import as separate entries" do
    first = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00")
    second = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")

    @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    entries = @account.entries.where(source: "enable_banking")
    assert_equal 2, entries.count
    assert_equal BigDecimal("9.00"), entries.find_by!(external_id: "enable_banking_tid-x").amount
    assert_equal BigDecimal("7.00"), entries.find_by!(external_id: sibling_id("r-b")).amount
  end

  test "an entry already stored under a shared transaction_id keeps its id when a sibling row arrives" do
    first = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00")
    second = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")

    @enable_banking_account.update!(raw_transactions_payload: [ first ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    legacy = @account.entries.find_by!(source: "enable_banking", external_id: "enable_banking_tid-x")

    @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
    2.times { EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process }

    assert_equal 2, @account.entries.where(source: "enable_banking").count
    assert_equal BigDecimal("9.00"), legacy.reload.amount
    assert_equal "enable_banking_tid-x", legacy.external_id
  end

  test "a row repeating a stored transaction_id and entry_reference does not create a second entry" do
    row = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00")

    @enable_banking_account.update!(raw_transactions_payload: [ row, row.dup ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal [ "enable_banking_tid-x" ], @account.entries.where(source: "enable_banking").pluck(:external_id)
  end

  test "a settled pending row leaving the payload does not move the legacy id" do
    pending = raw_shared_tid_transaction(entry_reference: "r-p", amount: "9.00").merge(status: "PDNG", _pending: true)
    first = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00")
    second = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")

    @enable_banking_account.update!(raw_transactions_payload: [ pending, first, second ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    before = @account.entries.where(source: "enable_banking").pluck(:id, :external_id, :amount).sort

    # The importer drops the pending row once its booked counterpart is fetched.
    @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal before, @account.entries.where(source: "enable_banking").pluck(:id, :external_id, :amount).sort
    assert_equal [ "enable_banking_tid-x", sibling_id("r-b") ], before.map(&:second).sort
    assert_not @account.entries.find_by!(external_id: "enable_banking_tid-x").transaction.pending?
  end

  test "rows sharing a transaction_id keep their ids when the stored order changes" do
    first = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00")
    second = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")

    @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    before = @account.entries.where(source: "enable_banking").pluck(:id, :external_id, :amount).sort

    @enable_banking_account.update!(raw_transactions_payload: [ second, first ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal before, @account.entries.where(source: "enable_banking").pluck(:id, :external_id, :amount).sort
  end

  test "an entry showing one of two rows sharing a transaction_id keeps that movement" do
    first = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00")
    second = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")

    # The state both rows leave when they share enable_banking_tid-x: the last one written.
    collapsed = create_transaction(
      account: @account, name: "Laundromat", date: 2.days.ago.to_date, amount: 7, currency: "EUR",
      external_id: "enable_banking_tid-x", source: "enable_banking"
    )

    @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal BigDecimal("7.00"), collapsed.reload.amount
    assert_equal "enable_banking_tid-x", collapsed.external_id
    assert_equal BigDecimal("9.00"), @account.entries.find_by!(external_id: sibling_id("r-a")).amount
    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end

  test "a user-edited entry showing one of the rows keeps the movement with its amount" do
    collapsed = create_transaction(
      account: @account, name: "Laundromat", date: 1.day.ago.to_date, amount: 7, currency: "EUR",
      external_id: "enable_banking_tid-x", source: "enable_banking"
    )
    collapsed.mark_user_modified!

    @enable_banking_account.update!(raw_transactions_payload: [
      raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"),
      raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")
    ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal [ [ "enable_banking_tid-x", BigDecimal("7.00") ], [ sibling_id("r-a"), BigDecimal("9.00") ] ],
                 @account.entries.where(source: "enable_banking").order(:external_id).pluck(:external_id, :amount)
  end

  test "a sibling's id does not change when a later row's transaction_id equals it" do
    rows = [ raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"), raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00") ]
    @enable_banking_account.update!(raw_transactions_payload: rows)
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    @account.entries.find_by!(external_id: sibling_id("r-b")).mark_user_modified!

    @enable_banking_account.update!(raw_transactions_payload: rows + [
      raw_shared_tid_transaction(entry_reference: "r-z", amount: "3.00").merge(transaction_id: "tid-x_r-b")
    ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal %w[3.0 7.0 9.0], @account.entries.where(source: "enable_banking").pluck(:amount).map(&:to_s).sort
  end

  test "rows with identical content and different entry_references stay separate entries" do
    @enable_banking_account.update!(raw_transactions_payload: [
      raw_shared_tid_transaction(entry_reference: "r-1", amount: "2.50"),
      raw_shared_tid_transaction(entry_reference: "r-2", amount: "2.50")
    ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal [ "enable_banking_tid-x", sibling_id("r-2") ], @account.entries.where(source: "enable_banking").pluck(:external_id).sort
  end

  test "a lone sibling with its own entry does not take over the plain id" do
    @enable_banking_account.update!(raw_transactions_payload: [
      raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"),
      raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")
    ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    @enable_banking_account.update!(raw_transactions_payload: [ raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00") ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal %w[7.0 9.0], @account.entries.where(source: "enable_banking").pluck(:amount).map(&:to_s).sort
  end

  test "a new sibling does not take over the plain id of an entry whose row left the payload" do
    first = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00").merge(booking_date: 40.days.ago.to_date.to_s)
    second = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")
    @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    @account.entries.find_by!(external_id: "enable_banking_tid-x").transaction.update!(provider_entry_reference: nil) # stored without its entry_reference

    # e.g. a relinked account whose first window misses r-a
    @enable_banking_account.update!(raw_transactions_payload: [ second, raw_shared_tid_transaction(entry_reference: "r-c", amount: "5.00") ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal %w[5.0 7.0 9.0], @account.entries.where(source: "enable_banking").pluck(:amount).map(&:to_s).sort
    assert_equal BigDecimal("9.00"), @account.entries.find_by!(external_id: "enable_banking_tid-x").amount
  end

  test "a lone new sibling does not overwrite a plain entry whose row left the payload" do
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00").merge(booking_date: 40.days.ago.to_date.to_s))

    # e.g. a relinked account whose first window holds only r-b
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00"))

    assert_equal BigDecimal("9.00"), @account.entries.find_by!(external_id: "enable_banking_tid-x").amount
    assert_equal BigDecimal("7.00"), @account.entries.find_by!(external_id: sibling_id("r-b")).amount
  end

  test "a lone row with a re-issued reference keeps a plain entry whose row left the payload" do
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"))
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a2", amount: "9.00"))

    assert_equal [ "enable_banking_tid-x" ], @account.entries.where(source: "enable_banking").pluck(:external_id)
  end

  test "an unchanged payload does not duplicate a plain entry whose amount the user edited, before or after unlocking it" do
    rows = [ raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"), raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00") ]
    @enable_banking_account.update!(raw_transactions_payload: rows)
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    plain = @account.entries.find_by!(external_id: "enable_banking_tid-x")
    plain.update!(amount: 9.50)
    plain.lock_saved_attributes!

    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    assert_equal %w[7.0 9.5], @account.entries.where(source: "enable_banking").pluck(:amount).map(&:to_s).sort

    plain.reload.unlock_for_sync!
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end

  test "a new sibling neither overwrites nor is swallowed by an edited plain entry whose row left the payload" do
    [ ->(e) { e.update!(amount: 9.50) && e.lock_saved_attributes! }, ->(e) { e.mark_user_modified! } ].each do |edit|
      @account.entries.where(source: "enable_banking").destroy_all
      first = raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00").merge(booking_date: 40.days.ago.to_date.to_s)
      second = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")
      @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
      EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
      edit.call(@account.entries.find_by!(external_id: "enable_banking_tid-x"))

      @enable_banking_account.update!(raw_transactions_payload: [ second, raw_shared_tid_transaction(entry_reference: "r-c", amount: "5.00") ])
      EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

      assert_equal 40.days.ago.to_date, @account.entries.find_by!(external_id: "enable_banking_tid-x").date
      assert_equal 3, @account.entries.where(source: "enable_banking").count
    end
  end

  test "an unchanged payload does not re-import a sibling onto a categorised pending hold" do
    pending = raw_shared_tid_transaction(entry_reference: "r-p", amount: "50.00").merge(status: "PDNG", _pending: true)
    @enable_banking_account.update!(raw_transactions_payload: [ pending ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    @account.entries.find_by!(external_id: "enable_banking_tid-x").mark_user_modified!
    booked = raw_shared_tid_transaction(entry_reference: "r-b", amount: "20.00")
    @enable_banking_account.update!(raw_transactions_payload: [ booked ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    @enable_banking_account.update!(raw_transactions_payload: [ booked, raw_shared_tid_transaction(entry_reference: "r-a", amount: "57.00") ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    before = @account.entries.where(source: "enable_banking").pluck(:external_id, :amount).sort

    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal before, @account.entries.where(source: "enable_banking").pluck(:external_id, :amount).sort
  end

  test "a sibling without entry_reference gets its own entry" do
    @enable_banking_account.update!(raw_transactions_payload: [
      raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"),
      raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00"),
      raw_shared_tid_transaction(entry_reference: nil, amount: "3.00")
    ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal %w[3.0 7.0 9.0], @account.entries.where(source: "enable_banking").pluck(:amount).map(&:to_s).sort
  end

  test "an entry showing one of the rows stays with the row of its direction" do
    refund = create_transaction(
      account: @account, name: "Laundromat", date: 2.days.ago.to_date, amount: -9, currency: "EUR",
      external_id: "enable_banking_tid-x", source: "enable_banking"
    )

    @enable_banking_account.update!(raw_transactions_payload: [
      raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"),
      raw_shared_tid_transaction(entry_reference: "r-b", amount: "9.00").merge(credit_debit_indicator: "CRDT")
    ])
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process

    assert_equal BigDecimal("-9.00"), refund.reload.amount
    assert_equal BigDecimal("9.00"), @account.entries.find_by!(external_id: sibling_id("r-a")).amount
  end
  test "a relink where the bank re-issued the plain row's entry_reference does not duplicate it" do
    other = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00")
    [ "r-a", "r-a2" ].each do |ref|
      @enable_banking_account.update!(raw_transactions_payload: [ raw_shared_tid_transaction(entry_reference: ref, amount: "9.00"), other ])
      EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
    end

    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end

  test "a numeric entry_reference keeps its plain entry" do
    @enable_banking_account.update!(raw_transactions_payload: [
      raw_shared_tid_transaction(entry_reference: 12345, amount: "9.00"),
      raw_shared_tid_transaction(entry_reference: 67890, amount: "7.00")
    ])
    2.times { EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process }

    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end
  def sync_shared(*rows)
    @enable_banking_account.update!(raw_transactions_payload: rows)
    EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
  end

  test "a relink with a re-issued reference does not duplicate an entry settled from a hold or date-edited" do
    other = raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00").merge(booking_date: 3.days.ago.to_date.to_s)
    hold = raw_shared_tid_transaction(entry_reference: nil, amount: "9.00")
      .merge(transaction_id: nil, booking_date: nil, value_date: 4.days.ago.to_date.to_s, status: "PDNG", _pending: true)
    sync_shared(hold)
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"), other)
    assert_equal 2, @account.entries.where(source: "enable_banking").count

    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a2", amount: "9.00"), other)
    assert_equal 2, @account.entries.where(source: "enable_banking").count

    plain = @account.entries.find_by!(external_id: "enable_banking_tid-x")
    plain.update!(date: 6.days.ago.to_date)
    plain.lock_saved_attributes!
    plain.mark_user_modified!
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a3", amount: "9.00"), other)
    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end

  test "a sibling booking alone before a categorised hold's own row does not keep the hold" do
    sync_shared(raw_shared_tid_transaction(entry_reference: nil, amount: "50.00").merge(status: "PDNG", _pending: true))
    @account.entries.find_by!(external_id: "enable_banking_tid-x").mark_user_modified!
    other = raw_shared_tid_transaction(entry_reference: "r-b", amount: "20.00").merge(booking_date: 3.days.ago.to_date.to_s)
    sync_shared(other)
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "50.00"), other)

    assert_equal [ 20, 50 ], @account.entries.where(source: "enable_banking").pluck(:amount).map(&:to_i).sort
  end
  test "two siblings booking before a categorised hold's own row do not keep the hold" do
    sync_shared(raw_shared_tid_transaction(entry_reference: nil, amount: "50.00").merge(status: "PDNG", _pending: true))
    @account.entries.find_by!(external_id: "enable_banking_tid-x").mark_user_modified!
    others = [ [ "r-b", "20.00" ], [ "r-c", "30.00" ] ].map do |ref, amount|
      raw_shared_tid_transaction(entry_reference: ref, amount: amount).merge(booking_date: 3.days.ago.to_date.to_s)
    end
    sync_shared(*others)
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "50.00"), *others)

    assert_equal [ 20, 30, 50 ], @account.entries.where(source: "enable_banking").pluck(:amount).map(&:to_i).sort
  end
  test "an unchanged payload does not re-import a sibling onto a pending hold a rule excluded" do
    sync_shared(raw_shared_tid_transaction(entry_reference: nil, amount: "50.00").merge(status: "PDNG", _pending: true))
    @account.entries.find_by!(external_id: "enable_banking_tid-x").enrich_attribute(:excluded, true, source: "rule")
    rows = [ raw_shared_tid_transaction(entry_reference: "r-a", amount: "57.00"),
             raw_shared_tid_transaction(entry_reference: "r-b", amount: "20.00").merge(booking_date: 3.days.ago.to_date.to_s) ]
    2.times { sync_shared(*rows) }

    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end

  test "a suffixed sibling does not claim an excluded pending entry its plain-id row owns" do
    sync_shared(raw_shared_tid_transaction(entry_reference: nil, amount: "7.00").merge(status: "PDNG", _pending: true, booking_date: 3.days.ago.to_date.to_s))
    @account.entries.find_by!(external_id: "enable_banking_tid-x").update!(excluded: true)
    rows = [ raw_shared_tid_transaction(entry_reference: "r-a", amount: "7.00"),
             raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00").merge(booking_date: 1.day.ago.to_date.to_s) ]
    2.times { sync_shared(*rows) }

    assert @account.entries.find_by!(external_id: "enable_banking_tid-x").excluded?
    assert_equal [ [ sibling_id("r-b"), BigDecimal("7.00") ] ],
                 @account.entries.where(source: "enable_banking", excluded: false).pluck(:external_id, :amount)
  end

  test "the plain id goes to the row in the stored entry's currency" do
    collapsed = create_transaction(
      account: @account, name: "Laundromat", date: 2.days.ago.to_date, amount: 7, currency: "EUR",
      external_id: "enable_banking_tid-x", source: "enable_banking"
    )
    collapsed.mark_user_modified!
    usd = raw_shared_tid_transaction(entry_reference: "r-u", amount: "7.00").deep_merge(transaction_amount: { currency: "usd" })
    sync_shared(usd, raw_shared_tid_transaction(entry_reference: "r-e", amount: "7.00"))

    assert_equal [ [ "enable_banking_tid-x", "EUR" ], [ sibling_id("r-u"), "USD" ] ],
                 @account.entries.where(source: "enable_banking").order(:external_id).pluck(:external_id, :currency)
  end

  test "the stored entry_reference leaves transaction details empty" do
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"), raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00"))
    entry = @account.entries.find_by!(external_id: "enable_banking_tid-x")

    assert_equal "r-a", entry.transaction.provider_entry_reference
    filter = Rule::ConditionFilter::TransactionDetails.new(Rule.new(family: @family, resource_type: "transaction"))
    assert_includes filter.apply(@family.transactions.joins(:entry), "is_null", nil).pluck(:id), entry.entryable_id
  end

  [ [ "manual duplicate", 0 ], [ "scheduled bill", 5 ] ].each do |kind, days_ahead|
    test "a suffixed sibling still claims its #{kind} when the plain entry is an excluded pending" do
      sync_shared(raw_shared_tid_transaction(entry_reference: nil, amount: "7.00").merge(status: "PDNG", _pending: true, booking_date: 3.days.ago.to_date.to_s))
      @account.entries.find_by!(external_id: "enable_banking_tid-x").update!(excluded: true)
      manual = create_transaction(account: @account, name: "Shop", date: 1.day.ago.to_date, amount: 7, currency: "EUR")
      manual.update_columns(created_at: days_ahead.days.ago) if days_ahead.positive?
      rows = [ raw_shared_tid_transaction(entry_reference: "r-a", amount: "7.00"),
               raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00").merge(booking_date: 1.day.ago.to_date.to_s) ]
      2.times { sync_shared(*rows) }

      assert_equal [ [ manual.id, sibling_id("r-b") ] ], @account.entries.where(excluded: false, amount: 7).pluck(:id, :external_id)
    end
  end

  test "a plain entry stored without its entry_reference keeps its row when its currency is locked" do
    sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"),
                raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00").merge(booking_date: 3.days.ago.to_date.to_s))
    plain = @account.entries.find_by!(external_id: "enable_banking_tid-x")
    plain.transaction.update_column(:provider_entry_reference, nil)
    plain.update!(currency: "USD")
    plain.lock_saved_attributes!
    assert_not plain.reload.user_modified?

    2.times do
      sync_shared(raw_shared_tid_transaction(entry_reference: "r-a", amount: "9.00"),
                  raw_shared_tid_transaction(entry_reference: "r-b", amount: "7.00").merge(booking_date: 3.days.ago.to_date.to_s))
    end

    assert_equal 2, @account.entries.where(source: "enable_banking").count
  end

  test "a legacy plain entry with a locked, changed currency keeps its original row" do
    legacy = create_transaction(
      account: @account, name: "Laundromat", date: 2.days.ago.to_date, amount: 7, currency: "GBP",
      external_id: "enable_banking_tid-x", source: "enable_banking"
    )
    legacy.update!(currency: "EUR")
    legacy.lock_saved_attributes!
    gbp = raw_shared_tid_transaction(entry_reference: "r-g", amount: "7.00").deep_merge(transaction_amount: { currency: "GBP" })
    eur = raw_shared_tid_transaction(entry_reference: "r-e", amount: "7.00").merge(booking_date: 1.day.ago.to_date.to_s)
    2.times { sync_shared(gbp, eur) }

    assert_equal [ [ "enable_banking_tid-x", "EUR" ], [ sibling_id("r-e"), "EUR" ] ].sort,
                 @account.entries.where(source: "enable_banking").pluck(:external_id, :currency).sort
  end

  [ [ "the original row first", false ], [ "the sibling first", true ] ].each do |order, sibling_first|
    test "a legacy plain entry with a locked, changed currency keeps its original row on the same date, #{order}" do
      legacy = create_transaction(
        account: @account, name: "Laundromat", date: 2.days.ago.to_date, amount: 7, currency: "GBP",
        external_id: "enable_banking_tid-x", source: "enable_banking"
      )
      legacy.update!(currency: "EUR")
      legacy.lock_saved_attributes!
      rows = [ raw_shared_tid_transaction(entry_reference: "r-g", amount: "7.00").deep_merge(transaction_amount: { currency: "GBP" }),
               raw_shared_tid_transaction(entry_reference: "r-e", amount: "7.00") ]
      rows.reverse! if sibling_first
      2.times { sync_shared(*rows) }

      assert_equal [ [ "enable_banking_tid-x", "EUR" ], [ sibling_id("r-e"), "EUR" ] ].sort,
                   @account.entries.where(source: "enable_banking").pluck(:external_id, :currency).sort
    end
  end

  test "a legacy plain entry with a locked currency gives a tie to the row not in that currency" do
    legacy = create_transaction(
      account: @account, name: "Laundromat", date: 2.days.ago.to_date, amount: 7, currency: "EUR",
      external_id: "enable_banking_tid-x", source: "enable_banking"
    )
    legacy.update!(currency: "USD")
    legacy.lock_saved_attributes!
    usd = raw_shared_tid_transaction(entry_reference: "r-u", amount: "7.00").deep_merge(transaction_amount: { currency: "USD" })
    2.times { sync_shared(usd, raw_shared_tid_transaction(entry_reference: "r-e", amount: "7.00")) }

    assert_equal [ [ "enable_banking_tid-x", "USD" ], [ sibling_id("r-u"), "USD" ] ],
                 @account.entries.where(source: "enable_banking").order(:external_id).pluck(:external_id, :currency)
  end
end