The personal finance app for everyone (by everyone)
Ruby
fix(enable-banking): don't import a movement twice when the identifier arrives late (#3462)
Alberto Martín773769ee4fb1
diff --git a/app/models/enable_banking_account/transactions/processor.rb b/app/models/enable_banking_account/transactions/processor.rbindex efa525d0a2..4f324cbbba 100644--- a/app/models/enable_banking_account/transactions/processor.rb+++ b/app/models/enable_banking_account/transactions/processor.rb@@ -28,6 +28,12 @@ class EnableBankingAccount::Transactions::Processor# merchant queries for every imported row.shared_known_merchant_names = enable_banking_account.current_account&.family&.known_merchant_names || []+ # Same reasoning: read once per sync batch. Scoped to the rows stored under a+ # synthesised content hash, which are the only ones a later identifier can+ # claim, so this does not grow with the account's history.+ shared_identifierless_external_ids =+ EnableBankingEntry::Processor.identifierless_external_ids_for(enable_banking_account.current_account)+# Pre-fetch external_ids that must not be re-imported.# One query per category per sync; O(1) Set lookup per transaction — avoids N+1.excluded_ids = if enable_banking_account.current_account@@ -72,7 +78,25 @@ class EnableBankingAccount::Transactions::Processor.compact.to_set- manually_merged_ids | auto_claimed_ids+ # 3. Superseded: rows whose synthesised external_id was claimed by the same+ # movement arriving later with an identifier the ASPSP had not yet+ # assigned. The stored raw payload still holds the identifierless row, so+ # without this it would be reimported as a separate transaction.+ superseded_ids = Transaction.joins(:entry)+ .where(entries: { account_id: account_id })+ .where("transactions.extra ? 'superseded_external_ids'")+ .joins(+ Arel.sql(<<~SQL.squish)+ CROSS JOIN LATERAL jsonb_array_elements_text(+ transactions.extra->'superseded_external_ids'+ ) AS superseded_id+ SQL+ )+ .pluck(Arel.sql("superseded_id"))+ .compact+ .to_set++ manually_merged_ids | auto_claimed_ids | superseded_idselseSet.newend@@ -91,7 +115,9 @@ class EnableBankingAccount::Transactions::Processortransaction_data,enable_banking_account: enable_banking_account,import_adapter: shared_adapter,- known_merchant_names: shared_known_merchant_names+ known_merchant_names: shared_known_merchant_names,+ identifierless_external_ids: shared_identifierless_external_ids,+ excluded_external_ids: excluded_ids).processif result.nil?@@ -99,6 +125,16 @@ class EnableBankingAccount::Transactions::Processorerrors << { index: index, transaction_id: transaction_data[:transaction_id], error: "No linked account" }elseimported_count += 1++ # An identifierless row just stored under its content hash becomes+ # claimable by the same movement appearing later in this very batch+ # carrying the identifier the ASPSP has since assigned. Pending rows stay+ # out, as they do in identifierless_external_ids_for: their settlement+ # belongs to ProviderImportAdapter's pending->booked reconciliation.+ if ext_id && EnableBankingEntry::Processor.identifierless?(transaction_data) &&+ !EnableBankingEntry::Processor.pending_payload?(transaction_data)+ shared_identifierless_external_ids.add(ext_id)+ endendrescue ArgumentError => efailed_count += 1diff --git a/app/models/enable_banking_entry/processor.rb b/app/models/enable_banking_entry/processor.rbindex cf0922b283..7484c509ee 100644--- a/app/models/enable_banking_entry/processor.rb+++ b/app/models/enable_banking_entry/processor.rb@@ -23,6 +23,21 @@ class EnableBankingEntry::Processor# inside "NAME IT" -- a real chain name observed in this issue's own data).MIN_KNOWN_MERCHANT_MATCH_LENGTH = 3+ # Prefix of the identifier synthesised for a transaction the ASPSP returned+ # with neither transaction_id nor entry_reference.+ CONTENT_ID_PREFIX = "enable_banking_content_"++ # extra key listing external_ids a transaction was previously stored under.+ #+ # Deliberately not auto_claimed_pending_ids. That key also makes+ # Account::ProviderImportAdapter#import_transaction keep the stored date and+ # ignore the incoming one, which is right for a pending row claimed by its+ # booked twin and wrong here: these are BOOK rows whose date the ASPSP may+ # still correct, and the key is never removed, so the date would freeze+ # permanently. EnableBankingAccount::Transactions::Processor reads both keys+ # into excluded_ids, which is the behaviour actually wanted.+ SUPERSEDED_IDS_KEY = "superseded_external_ids"+# enable_banking_transaction is the raw hash fetched from Enable Banking API# Transaction structure from Enable Banking:# {@@ -51,7 +66,59 @@ class EnableBankingEntry::Processorcontent = [ date, amount, currency, direction, creditor, debtor, remittance_key ].map(&:to_s).join("\x1F")return nil if content.gsub("\x1F", "").blank?- "enable_banking_content_#{Digest::MD5.hexdigest(content)}"+ "#{CONTENT_ID_PREFIX}#{Digest::MD5.hexdigest(content)}"+ end++ # True when the ASPSP supplied no identifier of its own, so compute_external_id+ # falls back to hashing the content.+ #+ # Read from the raw fields rather than from the synthesised id's prefix: an+ # ASPSP identifier may itself begin with "content_", which would make a real+ # identifier look synthesised and skip the claim below.+ #+ # @return [Boolean]+ def self.identifierless?(raw_transaction_data)+ data = raw_transaction_data.with_indifferent_access+ data[:transaction_id].blank? && data[:entry_reference].blank?+ end++ # True when the ASPSP has flagged this raw payload as not yet settled.+ #+ # Named pending_payload? rather than the bare pending? that Transaction#pending?+ # already uses, on purpose: this checks the incoming provider hash, not a+ # persisted row, and the two are easy to conflate at a glance.+ #+ # @return [Boolean]+ def self.pending_payload?(raw_transaction_data)+ raw_transaction_data.with_indifferent_access[:_pending] == true+ end++ # External ids of the rows stored under a synthesised content hash, which are+ # the only rows a later identifier can claim.+ #+ # Far smaller than the account's history: these are only the transactions the+ # ASPSP has not yet given an identifier to, which it typically does within a+ # day.+ #+ # Excludes pending rows deliberately: a pending row settling into a booked one+ # is Enable Banking's own pending->booked reconciliation's job+ # (Account::ProviderImportAdapter's pending_match), which matches and protects+ # that transition more conservatively than this claim mechanism does. Without+ # this exclusion a pending, identifierless row could be claimed here instead,+ # by a payload that has nothing to do with it settling.+ #+ # @return [Set<String>]+ def self.identifierless_external_ids_for(account)+ return Set.new if account.blank?++ prefix = ActiveRecord::Base.sanitize_sql_like(CONTENT_ID_PREFIX)+ Transaction.excluding_pending+ .joins(:entry)+ .where(entries: { account_id: account.id, source: "enable_banking" })+ .where("entries.external_id LIKE ?", "#{prefix}%")+ .pluck("entries.external_id")+ .compact+ .to_setend# known_merchant_names: optional pre-fetched Family#known_merchant_names, so a@@ -59,11 +126,19 @@ class EnableBankingEntry::Processor# EnableBankingAccount::Transactions::Processor) can compute it once instead of# 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).- def initialize(enable_banking_transaction, enable_banking_account:, import_adapter: nil, known_merchant_names: nil)+ #+ # 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.+ def initialize(enable_banking_transaction, enable_banking_account:, import_adapter: nil, known_merchant_names: nil,+ identifierless_external_ids: nil, excluded_external_ids: nil)@enable_banking_transaction = enable_banking_transaction@enable_banking_account = enable_banking_account@import_adapter = import_adapter@known_merchant_names = known_merchant_names+ @identifierless_external_ids = identifierless_external_ids+ @excluded_external_ids = excluded_external_idsenddef process@@ -76,6 +151,8 @@ class EnableBankingEntry::Processorreturn nilend+ claim_identifierless_predecessor!+beginimport_adapter.import_transaction(external_id: external_id,@@ -313,6 +390,101 @@ class EnableBankingEntry::Processor@known_merchant_names ||= account&.family&.known_merchant_names || []end+ def identifierless_external_ids+ @identifierless_external_ids ||= self.class.identifierless_external_ids_for(account)+ end++ def excluded_external_ids+ @excluded_external_ids ||= Set.new+ end++ # Re-key the row this movement was already imported under, when the ASPSP has+ # since given it an identifier.+ #+ # Some ASPSPs return a transaction with neither transaction_id nor+ # entry_reference on the day it happens and assign one once the statement+ # closes. compute_external_id prefers the identifier and falls back to a+ # content hash, so the same movement arrives under a second identity, does not+ # match existing_ids, and imports again.+ #+ # Re-keying rather than skipping means import_transaction upserts onto the row+ # that is already there, so its category, merchant and any transfer link+ # survive.+ #+ # @return [void]+ def claim_identifierless_predecessor!+ return if account.blank?+ return if self.class.identifierless?(data)+ # A pending row can carry a real transaction_id/entry_reference (unlike a+ # BOOK row without one, which is the case this method exists for) and+ # Enable Banking's own pending->booked reconciliation in+ # Account::ProviderImportAdapter already matches and protects that+ # transition more conservatively. Keeping this claim scoped to BOOK on both+ # sides avoids the two mechanisms fighting over the same row.+ return if self.class.pending_payload?(data)++ incoming = self.class.compute_external_id(data)+ return if incoming.blank?++ content_id = self.class.compute_external_id(data.except(:transaction_id, :entry_reference))+ return if content_id.blank? || !identifierless_external_ids.include?(content_id)++ # Already stored under its own identifier: nothing to claim, and re-keying+ # would collide with it. This also keeps two genuinely identical charges+ # apart within this mechanism -- the second finds the predecessor already+ # taken and imports as its own row. (Such charges only get this far when+ # they differ in transaction_id: EnableBankingItem::Importer's content-level+ # dedup collapses them otherwise, see #2720.) Only reached once a+ # predecessor has been found, so it costs a query per claim rather than one+ # per transaction.+ return if account.entries.exists?(source: "enable_banking", external_id: incoming)++ predecessor = account.entries.find_by(source: "enable_banking", external_id: content_id)+ return if predecessor.nil?++ # Both writes or neither. A re-key whose superseded record was lost would+ # leave the next sync free to reimport the identifierless payload row as a+ # fresh duplicate, which is the bug this method exists to prevent.+ #+ # The row is locked and re-read inside the transaction because the+ # predecessor was found outside it: EnableBankingItem::Syncer#perform_sync+ # processes transactions before scheduling account syncs, so two overlapping+ # item syncs can reach the same row. Re-checking external_id under the lock+ # means the second one steps aside instead of overwriting the identifier the+ # first just assigned.+ claimed = false+ ActiveRecord::Base.transaction do+ predecessor.lock!+ next unless predecessor.external_id == content_id++ predecessor.update_column(:external_id, incoming)+ record_superseded_identifier!(predecessor, content_id)+ claimed = true+ end+ return unless claimed++ identifierless_external_ids.delete(content_id)+ excluded_external_ids.add(content_id)+ end++ # Record the identifier a row no longer answers to.+ #+ # The stored raw payload is never pruned and every sync re-walks all of it, so+ # without this the identifierless row would find nothing under its content+ # hash and insert a duplicate on the next run.+ #+ # @return [void]+ def record_superseded_identifier!(entry, abandoned_id)+ transaction = entry.entryable+ return unless transaction.is_a?(Transaction)++ extra = transaction.extra.presence || {}+ recorded = Array(extra[SUPERSEDED_IDS_KEY])+ return if recorded.include?(abandoned_id)++ transaction.update_column(:extra, extra.merge(SUPERSEDED_IDS_KEY => recorded + [ abandoned_id ]))+ end+def merchant_name_candidatecounterparty = counterparty_name.to_s.stripreturn counterparty if counterparty.present? && !technical_card_counterparty?(counterparty)diff --git a/test/models/enable_banking_account/transactions/processor_test.rb b/test/models/enable_banking_account/transactions/processor_test.rbindex 81426dce3c..2623e2673f 100644--- a/test/models/enable_banking_account/transactions/processor_test.rb+++ b/test/models/enable_banking_account/transactions/processor_test.rb@@ -35,6 +35,67 @@ class EnableBankingAccount::Transactions::ProcessorTest < ActiveSupport::TestCas}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 "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" dopending_ext_id = "enable_banking_PDNG_MERGED"diff --git a/test/models/enable_banking_entry/processor_test.rb b/test/models/enable_banking_entry/processor_test.rbindex 7ad51044c6..bfb01593e4 100644--- a/test/models/enable_banking_entry/processor_test.rb+++ b/test/models/enable_banking_entry/processor_test.rb@@ -291,6 +291,175 @@ class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCaseendend+ # --- 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