Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(enable-banking): keep distinct booked references apart (#4566)

Rubén García5bcbe76470d2
diff --git a/app/models/enable_banking_account/transactions/processor.rb b/app/models/enable_banking_account/transactions/processor.rb
index 7db553ff95..b9a9cfe126 100644
--- a/app/models/enable_banking_account/transactions/processor.rb
+++ b/app/models/enable_banking_account/transactions/processor.rb
@@ -101,7 +101,9 @@ class EnableBankingAccount::Transactions::Processor
Set.new
end
- rows_in_import_order.each do |transaction_data, index|
+ pending_external_ids = open_pending_external_ids
+
+ rows_in_settlement_order(pending_external_ids).each do |transaction_data, index|
begin
ext_id = external_ids[index]
@@ -118,7 +120,8 @@ class EnableBankingAccount::Transactions::Processor
known_merchant_names: shared_known_merchant_names,
identifierless_external_ids: shared_identifierless_external_ids,
excluded_external_ids: excluded_ids,
- external_id: ext_id
+ external_id: ext_id,
+ pending_external_ids: pending_external_ids
).process
if result.nil?
@@ -186,4 +189,61 @@ class EnableBankingAccount::Transactions::Processor
[ external_ids[index] == EnableBankingEntry::Processor.compute_external_id(data) ? 0 : 1, index ]
end
end
+
+ # External ids of the account's stored pending entries.
+ #
+ # @return [Set<String>]
+ def open_pending_external_ids
+ account = enable_banking_account.current_account
+ return Set.new if account.blank?
+
+ Transaction.pending
+ .joins(:entry)
+ .where(entries: { account_id: account.id, source: "enable_banking" })
+ .pluck("entries.external_id")
+ .compact
+ .to_set
+ end
+
+ # A booked row that identifies a stored pending entry, by its own external_id
+ # or by its entry_reference, settles that entry. Importing those rows first
+ # keeps another booked row of the same amount from claiming the entry
+ # through ProviderImportAdapter's amount-based pending match, which would
+ # move the pending entry's notes and edits onto the wrong operation.
+ #
+ # An identifierless booked copy of a settling row still goes ahead of it, so
+ # the settling row claims that copy's entry as its predecessor instead of
+ # the copy importing as a second entry.
+ #
+ # A settling row whose content key raises is left out of that match:
+ # processing it raises again inside its own rescue, which records the
+ # failure against that row. Within each group, rows keep
+ # rows_in_import_order. Indexes remain those of the stored payload, for
+ # error reporting.
+ #
+ # @return [Array<Array(Hash, Integer)>]
+ def rows_in_settlement_order(pending_external_ids)
+ rows = rows_in_import_order
+ return rows if pending_external_ids.empty?
+
+ settling, others = rows.partition do |transaction_data, index|
+ EnableBankingEntry::Processor.settled_pending_external_id(
+ transaction_data, pending_external_ids, external_id: external_ids[index]
+ ).present?
+ end
+ return rows if settling.empty?
+
+ settling_content_ids = settling.filter_map do |transaction_data, _index|
+ EnableBankingEntry::Processor.content_external_id(transaction_data)
+ rescue StandardError
+ nil
+ end.to_set
+
+ predecessors, others = others.partition do |transaction_data, _index|
+ EnableBankingEntry::Processor.identifierless?(transaction_data) &&
+ !EnableBankingEntry::Processor.pending_payload?(transaction_data) &&
+ settling_content_ids.include?(EnableBankingEntry::Processor.content_external_id(transaction_data))
+ end
+ predecessors + settling + others
+ end
end
diff --git a/app/models/enable_banking_entry/processor.rb b/app/models/enable_banking_entry/processor.rb
index d8e1c29342..7a35196e94 100644
--- a/app/models/enable_banking_entry/processor.rb
+++ b/app/models/enable_banking_entry/processor.rb
@@ -146,6 +146,14 @@ class EnableBankingEntry::Processor
data[:transaction_id].blank? && data[:entry_reference].blank?
end
+ # External id of the movement's identifierless copy: its content hash, which
+ # a later identified row claims as its predecessor.
+ #
+ # @return [String, nil]
+ def self.content_external_id(raw_transaction_data)
+ compute_external_id(raw_transaction_data.with_indifferent_access.except(:transaction_id, :entry_reference))
+ end
+
def self.party_name(data, key)
value = data[key]
nested = value.is_a?(Hash) ? value[:name] : (value if value.is_a?(String))
@@ -253,6 +261,25 @@ class EnableBankingEntry::Processor
data[:_pending] == true || unidentified_hold?(data)
end
+ # External id of the stored pending entry this payload settles, when the ASPSP
+ # identifies it: the payload's own external_id, or its entry_reference when a
+ # transaction_id assigned at booking changed the external_id.
+ #
+ # @param pending_external_ids [Set<String>] stored pending entries still open
+ # @param external_id [String, nil] the row's id from external_ids_for, when it
+ # differs from compute_external_id because rows share a transaction_id
+ # @return [String, nil]
+ def self.settled_pending_external_id(raw_transaction_data, pending_external_ids, external_id: nil)
+ return if pending_external_ids.blank?
+
+ data = raw_transaction_data.with_indifferent_access
+ return if pending_payload?(data)
+
+ reference = data[:entry_reference].presence
+ candidates = [ external_id || compute_external_id(data), ("enable_banking_#{reference}" if reference) ]
+ candidates.compact.find { |id| pending_external_ids.include?(id) }
+ end
+
# External ids of the rows stored under a synthesised content hash, which are
# the only rows a later identifier can claim.
#
@@ -287,15 +314,16 @@ class EnableBankingEntry::Processor
# once per row -- same pattern as the shared import_adapter. Falls back to
# fetching it lazily per-instance when not provided (e.g. in isolation/tests).
#
- # identifierless_external_ids / excluded_external_ids: the batch's live sets,
- # same pattern again. Both are mutated as claims happen, so a row later in the
- # same batch sees what earlier rows did -- excluded_ids in the batch processor
- # is built once, before the loop, and would otherwise be stale.
+ # identifierless_external_ids / excluded_external_ids / pending_external_ids:
+ # the batch's live sets, same pattern again. All are mutated as claims happen,
+ # so a row later in the same batch sees what earlier rows did -- excluded_ids
+ # in the batch processor is built once, before the loop, and would otherwise
+ # be stale.
#
# external_id: this row's id from external_ids_for over the whole payload,
# which can differ from compute_external_id when rows share a transaction_id.
def initialize(enable_banking_transaction, enable_banking_account:, import_adapter: nil, known_merchant_names: nil,
- identifierless_external_ids: nil, excluded_external_ids: nil, external_id: nil)
+ identifierless_external_ids: nil, excluded_external_ids: nil, external_id: nil, pending_external_ids: nil)
@enable_banking_transaction = enable_banking_transaction
@external_id = external_id
@enable_banking_account = enable_banking_account
@@ -303,6 +331,7 @@ class EnableBankingEntry::Processor
@known_merchant_names = known_merchant_names
@identifierless_external_ids = identifierless_external_ids
@excluded_external_ids = excluded_external_ids
+ @pending_external_ids = pending_external_ids
end
def process
@@ -326,6 +355,8 @@ class EnableBankingEntry::Processor
first_hold_import = unidentified_hold? &&
!account.entries.exists?(source: "enable_banking", external_id: safe_id)
+ settled_pending_id = self.class.settled_pending_external_id(data, pending_external_ids, external_id: @external_id)
+
entry = begin
import_adapter.import_transaction(
external_id: external_id,
@@ -338,7 +369,10 @@ class EnableBankingEntry::Processor
allow_heuristic_matching: !plain_sibling_pending_match?,
notes: notes,
extra: extra,
- investment_activity_label: investment_activity_label
+ investment_activity_label: investment_activity_label,
+ # Claims that exact pending entry before the adapter falls back to
+ # matching any pending entry of the same amount.
+ pending_transaction_id: (settled_pending_id unless settled_pending_id == external_id)
)
rescue ArgumentError => e
Rails.logger.error "EnableBankingEntry::Processor - Validation error for transaction #{safe_id}: #{e.message}"
@@ -354,6 +388,7 @@ class EnableBankingEntry::Processor
store_entry_reference(entry) if import_adapter.skipped_entries.size == skips
capture_unidentified_hold_diagnostic(entry, external_id: safe_id) if first_hold_import && entry
+ pending_external_ids.delete(settled_pending_id) if entry && settled_pending_id
entry
end
@@ -701,6 +736,10 @@ class EnableBankingEntry::Processor
@excluded_external_ids ||= Set.new
end
+ def pending_external_ids
+ @pending_external_ids ||= Set.new
+ end
+
# Re-key the row this movement was already imported under, when the ASPSP has
# since given it an identifier.
#
@@ -729,7 +768,7 @@ class EnableBankingEntry::Processor
incoming = @external_id || self.class.compute_external_id(data)
return if incoming.blank?
- content_id = self.class.compute_external_id(data.except(:transaction_id, :entry_reference))
+ content_id = self.class.content_external_id(data)
return if content_id.blank? || !identifierless_external_ids.include?(content_id)
# Already stored under its own identifier: nothing to claim, and re-keying
diff --git a/test/fixtures/files/enable_banking/distinct_booked_top_ups.json b/test/fixtures/files/enable_banking/distinct_booked_top_ups.json
new file mode 100644
index 0000000000..bf1365d2d9
--- /dev/null
+++ b/test/fixtures/files/enable_banking/distinct_booked_top_ups.json
@@ -0,0 +1,48 @@
+[
+ {
+ "entry_reference": "reference-a",
+ "transaction_id": null,
+ "booking_date": "2026-01-15",
+ "value_date": "2026-01-15",
+ "transaction_date": null,
+ "transaction_amount": {
+ "currency": "EUR",
+ "amount": "12.00"
+ },
+ "credit_debit_indicator": "DBIT",
+ "remittance_information": [
+ "Synthetic card top-up"
+ ],
+ "status": "BOOK",
+ "reference_number": null,
+ "merchant_category_code": null,
+ "bank_transaction_code": {
+ "description": null,
+ "code": "PMNT",
+ "sub_code": null
+ }
+ },
+ {
+ "entry_reference": "reference-b",
+ "transaction_id": null,
+ "booking_date": "2026-01-15",
+ "value_date": "2026-01-15",
+ "transaction_date": null,
+ "transaction_amount": {
+ "currency": "EUR",
+ "amount": "12.00"
+ },
+ "credit_debit_indicator": "DBIT",
+ "remittance_information": [
+ "Synthetic card top-up"
+ ],
+ "status": "BOOK",
+ "reference_number": null,
+ "merchant_category_code": null,
+ "bank_transaction_code": {
+ "description": null,
+ "code": "PMNT",
+ "sub_code": null
+ }
+ }
+]
diff --git a/test/models/enable_banking_account/transactions/processor_test.rb b/test/models/enable_banking_account/transactions/processor_test.rb
index 9644ebe30e..207c4dff02 100644
--- a/test/models/enable_banking_account/transactions/processor_test.rb
+++ b/test/models/enable_banking_account/transactions/processor_test.rb
@@ -249,6 +249,71 @@ class EnableBankingAccount::Transactions::ProcessorTest < ActiveSupport::TestCas
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
diff --git a/test/models/enable_banking_item/importer_booked_references_test.rb b/test/models/enable_banking_item/importer_booked_references_test.rb
new file mode 100644
index 0000000000..f25abb7b74
--- /dev/null
+++ b/test/models/enable_banking_item/importer_booked_references_test.rb
@@ -0,0 +1,330 @@
+require "test_helper"
+
+class EnableBankingItem::ImporterBookedReferencesTest < ActiveSupport::TestCase
+ setup do
+ @account = accounts(:depository)
+ @account.update!(currency: "EUR")
+ @item = EnableBankingItem.create!(
+ family: @account.family,
+ name: "Test bank",
+ country_code: "ES",
+ application_id: "test_app_id",
+ client_certificate: "test_cert",
+ session_id: "test_session",
+ session_expires_at: 1.day.from_now,
+ sync_start_date: 1.month.ago.to_date
+ )
+ @provider_account = EnableBankingAccount.create!(
+ enable_banking_item: @item,
+ name: "Current account",
+ uid: "test-booked-references",
+ account_id: "65b1cf69-2bb8-4ea5-b059-73621df32098",
+ currency: "EUR"
+ )
+ AccountProvider.create!(account: @account, provider: @provider_account)
+ @provider = mock()
+ @provider.stubs(:get_session).returns(accounts: [ @provider_account.uid ])
+ @provider.stubs(:get_account_balances).returns(
+ balances: [ { balance_type: "CLBD", balance_amount: { amount: "100.00", currency: "EUR" } } ]
+ )
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [])
+ @importer = EnableBankingItem::Importer.new(@item, enable_banking_provider: @provider)
+ end
+
+ test "imports both booked operations when only their bank references differ" do
+ rows = JSON.parse(file_fixture("enable_banking/distinct_booked_top_ups.json").read)
+ rows.each do |tx|
+ tx["booking_date"] = tx["value_date"] = Date.current.to_s
+ end
+ provide_booked_rows(rows)
+
+ import_and_process
+
+ assert_equal %w[reference-a reference-b], stored_references
+ assert_equal %w[enable_banking_reference-a enable_banking_reference-b], imported_entries.pluck(:external_id).sort
+ assert_equal [ BigDecimal("12.00"), BigDecimal("12.00") ], imported_entries.order(:external_id).pluck(:amount)
+ end
+
+ test "imports a booked operation repeated under the same reference only once" do
+ provide_booked_rows([ booked("reference-a"), booked("reference-a") ])
+
+ import_and_process
+
+ assert_equal [ "reference-a" ], stored_references
+ assert_equal 1, imported_entries.count
+ end
+
+ test "preserves distinct references when the booked endpoint omits status" do
+ rows = [ booked("reference-a"), booked("reference-b") ].map { |tx| tx.except(:status) }
+ provide_booked_rows(rows)
+
+ import_and_process
+
+ assert_equal %w[reference-a reference-b], stored_references
+ assert_equal 2, imported_entries.count
+ assert_equal BigDecimal("24.00"), imported_entries.sum(:amount)
+
+ assert_no_difference -> { imported_entries.count } do
+ import_and_process
+ end
+ end
+
+ test "does not treat rows without status from the pending endpoint as booked" do
+ @importer.stubs(:include_pending?).returns(true)
+ provide_booked_rows([])
+ rows = [ booked("pending-a"), booked("pending-b") ].map { |tx| tx.except(:status) }
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: rows)
+
+ import_and_process
+
+ assert_equal [ "pending-a" ], stored_references
+ assert_equal 1, imported_entries.count
+ assert imported_entries.sole.transaction.pending?
+ end
+
+ test "adds only a missing reference and preserves reviewed entries across repeated imports" do
+ provide_booked_rows([ booked("reference-a") ])
+ import_and_process
+ original = imported_entries.sole
+ original.update!(notes: "Reviewed transaction")
+ original.mark_user_modified!
+
+ provide_booked_rows([ booked("reference-b"), booked("reference-a") ])
+
+ assert_difference -> { imported_entries.count }, 1 do
+ import_and_process
+ end
+ ids = imported_entries.pluck(:id).sort
+ assert_equal "Reviewed transaction", original.reload.notes
+
+ assert_no_difference -> { imported_entries.count } do
+ import_and_process
+ end
+ assert_equal ids, imported_entries.pluck(:id).sort
+ assert_equal %w[reference-a reference-b], stored_references
+ assert_equal "Reviewed transaction", original.reload.notes
+ end
+
+ test "imports a repeated reference only once when pages overlap" do
+ first = booked("reference-a")
+ second = booked("reference-b")
+ @provider.stubs(:get_account_transactions)
+ .with(has_entries(transaction_status: "BOOK", continuation_key: nil))
+ .returns(transactions: [ first ], continuation_key: "next-page")
+ @provider.stubs(:get_account_transactions)
+ .with(has_entries(transaction_status: "BOOK", continuation_key: "next-page"))
+ .returns(transactions: [ first.deep_stringify_keys, second ])
+
+ import_and_process
+
+ assert_equal %w[reference-a reference-b], stored_references
+ assert_equal 2, imported_entries.count
+ end
+
+ test "prefers booked references over matching pending copies regardless of response order" do
+ @importer.stubs(:include_pending?).returns(true)
+ pending = booked("pending-reference").merge(status: "PDNG")
+ provide_booked_rows([ pending, booked("reference-a"), booked("reference-b") ])
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [ pending ])
+
+ import_and_process
+
+ assert_equal %w[reference-a reference-b], stored_references
+ assert_equal 2, imported_entries.count
+ assert imported_entries.all? { |entry| !entry.transaction.pending? }
+ end
+
+ test "preserves two distinct incoming top-ups as separate ledger credits" do
+ rows = [ booked("reference-a"), booked("reference-b") ].map { |tx| tx.merge(credit_debit_indicator: "CRDT") }
+ provide_booked_rows(rows)
+
+ import_and_process
+
+ assert_equal 2, imported_entries.count
+ assert_equal BigDecimal("-24.00"), imported_entries.sum(:amount)
+ end
+
+ test "settles a previously imported pending operation without losing the second booked reference" do
+ @importer.stubs(:include_pending?).returns(true)
+ provide_booked_rows([])
+ pending = booked("pending-reference").merge(status: "PDNG")
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [ pending ])
+ import_and_process
+ original = imported_entries.sole
+ assert original.transaction.pending?
+
+ provide_booked_rows([ booked("reference-a"), booked("reference-b") ])
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [])
+
+ assert_difference -> { imported_entries.count }, 1 do
+ import_and_process
+ end
+
+ assert_equal %w[enable_banking_reference-a enable_banking_reference-b], imported_entries.pluck(:external_id).sort
+ assert imported_entries.exists?(original.id)
+ assert imported_entries.all? { |entry| !entry.transaction.pending? }
+
+ assert_no_difference -> { imported_entries.count } do
+ import_and_process
+ end
+ end
+
+ test "settles a stored pending entry by its own reference when a booked twin comes first" do
+ @importer.stubs(:include_pending?).returns(true)
+ provide_booked_rows([])
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG"))
+ .returns(transactions: [ booked("reference-b").merge(status: "PDNG") ])
+ import_and_process
+ original = imported_entries.sole
+ assert original.transaction.pending?
+ original.update!(notes: "Reviewed while pending")
+ original.mark_user_modified!
+
+ provide_booked_rows([ booked("reference-a"), booked("reference-b") ])
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [])
+
+ assert_difference -> { imported_entries.count }, 1 do
+ import_and_process
+ end
+
+ original.reload
+ assert_equal "enable_banking_reference-b", original.external_id
+ assert_equal "Reviewed while pending", original.notes
+ assert_not original.transaction.pending?
+ assert_not_equal "Reviewed while pending", imported_entries.find_by!(external_id: "enable_banking_reference-a").notes
+
+ assert_no_difference -> { imported_entries.count } do
+ import_and_process
+ end
+ assert_equal "enable_banking_reference-b", original.reload.external_id
+ end
+
+ test "settles a stored pending entry by its reference when its booked row gains a transaction_id" do
+ @importer.stubs(:include_pending?).returns(true)
+ provide_booked_rows([ booked("reference-a") ])
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG"))
+ .returns(transactions: [ authorisation("reference-b", "Synthetic card authorisation") ])
+ import_and_process
+ original = imported_entries.find_by!(external_id: "enable_banking_reference-b")
+ assert original.transaction.pending?
+ original.update!(notes: "Reviewed while pending")
+ original.lock_saved_attributes!
+ original.mark_user_modified!
+
+ provide_booked_rows([
+ booked("reference-a"),
+ booked("reference-c"),
+ booked("reference-b").merge(transaction_id: "transaction-b")
+ ])
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [])
+
+ assert_difference -> { imported_entries.count }, 1 do
+ import_and_process
+ end
+
+ original.reload
+ assert_equal "enable_banking_transaction-b", original.external_id
+ assert_equal "Reviewed while pending", original.notes
+ assert_not original.transaction.pending?
+ assert_not_equal "Reviewed while pending", imported_entries.find_by!(external_id: "enable_banking_reference-c").notes
+
+ assert_no_difference -> { imported_entries.count } do
+ import_and_process
+ end
+ assert_equal "enable_banking_transaction-b", original.reload.external_id
+ end
+
+ test "settles the pending entry with its own reference when several share the amount" do
+ @importer.stubs(:include_pending?).returns(true)
+ provide_booked_rows([])
+ older = authorisation("reference-b", "Synthetic authorisation one", date: 1.day.ago.to_date)
+ newer = authorisation("reference-d", "Synthetic authorisation two")
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [ older, newer ])
+ import_and_process
+ original = imported_entries.find_by!(external_id: "enable_banking_reference-b")
+
+ provide_booked_rows([ booked("reference-b").merge(transaction_id: "transaction-b") ])
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "PDNG")).returns(transactions: [ newer ])
+
+ assert_no_difference -> { imported_entries.count } do
+ import_and_process
+ end
+
+ assert_equal "enable_banking_transaction-b", original.reload.external_id
+ assert_not original.transaction.pending?
+ assert imported_entries.find_by!(external_id: "enable_banking_reference-d").transaction.pending?
+ end
+
+ test "retains fallback matching when the bank supplies no references" do
+ row = booked(nil).merge(creditor: { name: "Synthetic merchant" })
+ provide_booked_rows([ row, row.deep_dup ])
+
+ import_and_process
+
+ assert_equal 1, imported_entries.count
+ assert_match(/\Aenable_banking_content_/, imported_entries.sole.external_id)
+ end
+
+ test "claims an identifierless predecessor once when two booked references arrive" do
+ row = booked(nil).merge(creditor: { name: "Synthetic merchant" })
+ provide_booked_rows([ row ])
+ import_and_process
+ original = imported_entries.sole
+ original.update!(notes: "Reviewed before settlement")
+ original.mark_user_modified!
+ provide_booked_rows([ row.merge(entry_reference: "reference-a"), row.merge(entry_reference: "reference-b") ])
+
+ assert_difference -> { imported_entries.count }, 1 do
+ import_and_process
+ end
+
+ assert_equal "Reviewed before settlement", original.reload.notes
+ assert_equal %w[enable_banking_reference-a enable_banking_reference-b], imported_entries.pluck(:external_id).sort
+
+ assert_no_difference -> { imported_entries.count } do
+ import_and_process
+ end
+ end
+
+ private
+ def booked(reference)
+ {
+ entry_reference: reference,
+ transaction_id: nil,
+ booking_date: Date.current.to_s,
+ value_date: Date.current.to_s,
+ transaction_amount: { amount: "12.00", currency: "EUR" },
+ credit_debit_indicator: "DBIT",
+ remittance_information: [ "Synthetic card top-up" ],
+ status: "BOOK"
+ }
+ end
+
+ def authorisation(reference, description, date: Date.current)
+ booked(reference).merge(
+ status: "PDNG",
+ booking_date: date.to_s,
+ value_date: date.to_s,
+ remittance_information: [ description ]
+ )
+ end
+
+ def provide_booked_rows(rows)
+ @provider.stubs(:get_account_transactions).with(has_entries(transaction_status: "BOOK")).returns(transactions: rows)
+ end
+
+ def import_and_process
+ result = @importer.import
+ assert result[:success], result.inspect
+ processing = EnableBankingAccount::Transactions::Processor.new(@provider_account.reload).process
+ assert processing[:success], processing.inspect
+ end
+
+ def stored_references
+ @provider_account.reload.raw_transactions_payload.map { |tx| tx["entry_reference"] }.sort
+ end
+
+ def imported_entries
+ @account.entries.where(source: "enable_banking", entryable_type: "Transaction")
+ end
+end