The personal finance app for everyone (by everyone)
Ruby
Keep Enable Banking rows that share a transaction_id apart (#4970)
arnaurodondev579ab21239bf
diff --git a/app/models/enable_banking_account/transactions/processor.rb b/app/models/enable_banking_account/transactions/processor.rbindex 4f324cbbba..7db553ff95 100644--- a/app/models/enable_banking_account/transactions/processor.rb+++ b/app/models/enable_banking_account/transactions/processor.rb@@ -101,9 +101,9 @@ class EnableBankingAccount::Transactions::ProcessorSet.newend- enable_banking_account.raw_transactions_payload.each_with_index do |transaction_data, index|+ rows_in_import_order.each do |transaction_data, index|begin- ext_id = EnableBankingEntry::Processor.compute_external_id(transaction_data)+ ext_id = external_ids[index]if ext_id && excluded_ids.include?(ext_id)Rails.logger.info("EnableBankingAccount::Transactions::Processor - Skipping re-import of manually merged pending transaction: #{ext_id}")@@ -117,7 +117,8 @@ class EnableBankingAccount::Transactions::Processorimport_adapter: shared_adapter,known_merchant_names: shared_known_merchant_names,identifierless_external_ids: shared_identifierless_external_ids,- excluded_external_ids: excluded_ids+ excluded_external_ids: excluded_ids,+ external_id: ext_id).processif result.nil?@@ -169,4 +170,20 @@ class EnableBankingAccount::Transactions::Processorresultend++ private++ def external_ids+ @external_ids ||= EnableBankingEntry::Processor.external_ids_for(+ enable_banking_account.raw_transactions_payload, account: enable_banking_account.current_account+ )+ end++ # Rows keeping their plain id go first, so a pending entry under a shared+ # transaction_id settles into the row that keeps that id, not a same-amount sibling.+ def rows_in_import_order+ enable_banking_account.raw_transactions_payload.each_with_index.sort_by do |data, index|+ [ external_ids[index] == EnableBankingEntry::Processor.compute_external_id(data) ? 0 : 1, index ]+ end+ endenddiff --git a/app/models/enable_banking_entry/processor.rb b/app/models/enable_banking_entry/processor.rbindex ae201f8635..d8e1c29342 100644--- a/app/models/enable_banking_entry/processor.rb+++ b/app/models/enable_banking_entry/processor.rb@@ -2,6 +2,7 @@ require "digest/md5"class EnableBankingEntry::Processorinclude CurrencyNormalizable+ extend CurrencyNormalizableinclude CardAuthorizationHold# Small-merchant card terminal providers that prefix the payee with "KEYWORD *"@@ -77,6 +78,61 @@ class EnableBankingEntry::Processor"#{CONTENT_ID_PREFIX}#{Digest::MD5.hexdigest(content)}"end+ # One external id per raw row. transaction_id is not guaranteed unique, so booked+ # rows sharing one are told apart by entry_reference: one keeps+ # enable_banking_<transaction_id> (the row with its own suffixed entry never does;+ # otherwise the best match for the entry stored under the plain id, else the first),+ # the others get enable_banking_<transaction_id>_<MD5(entry_reference)>.+ # Pending rows keep compute_external_id.+ #+ # @return [Array<String, nil>]+ def self.external_ids_for(raw_transactions, account: nil)+ rows = raw_transactions.map(&:with_indifferent_access)+ ids = rows.map { |data| compute_external_id(data) }+ ref = ->(i) { rows[i][:entry_reference].to_s }+ suffixed = ->(i) { "#{ids[i]}_#{Digest::MD5.hexdigest(ref[i])}" }+ groups = rows.each_index.select { |i| rows[i][:transaction_id].present? && !pending_payload?(rows[i]) }.group_by { |i| ids[i] }+ stored = account ? account.entries.where(source: "enable_banking", external_id: groups.flat_map { |id, is| [ id, *is.map(&suffixed) ] }).includes(:entryable).index_by(&:external_id) : {}++ groups.each do |legacy_id, indexes|+ free = indexes.reject { |i| stored.key?(suffixed[i]) }+ legacy = stored[legacy_id]+ kept = legacy&.entryable.try(:provider_entry_reference)+ # Without a stored reference, a locked currency is the owner's change, not the bank's: match on amount and date+ # only. On a tie the row not in the locked currency wins, since the owner changed the entry away from its row's.+ match_currency = kept.present? || !legacy&.locked?(:currency)+ score = ->(i) { movement_match(legacy, rows[i], account, match_currency: match_currency) }+ other_currency = ->(i) { !match_currency && movement_match(legacy, rows[i], account).zero? ? 1 : 0 }+ # Rows that already have a suffixed entry never take the plain id; if all do, nobody does (no duplicate).+ owner = free.each_with_index.max_by { |i, pos| [ score[i], other_currency[i], -pos ] }&.first+ # The plain entry stores its row's entry_reference. Without one (older entries): a sibling already has its+ # own entry, so the plain one is another row's unless its amount matches or was edited.+ owner = free.find { |i| ref[i] == kept } if kept && indexes.any? { |i| ref[i] == kept }+ # A stored reference missing from the payload (re-issued, or aged out): keep the entry only on an exact match.+ # The entry's date is not the bank's when the user locked it or a settled hold froze it: an amount match is then exact.+ own_date = legacy && (legacy.locked?(:date) || legacy.entryable.try(:extra)&.key?("auto_claimed_pending_ids"))+ owner = nil if kept && indexes.none? { |i| ref[i] == kept } && owner && score[owner] < (own_date ? 1 : 2)+ owner = nil if !kept && owner && legacy && free.size < indexes.size && score[owner].zero? && !legacy.protected_from_sync? && !legacy.locked?(:amount) && !legacy.locked?(:currency)+ indexes.each { |i| ids[i] = suffixed[i] unless owner && ref[i] == ref[owner] }+ end+ ids+ end++ # 2: same signed amount, currency and date as the entry; 1: same signed amount and currency; 0: neither.+ # match_currency: false leaves the currency out.+ def self.movement_match(entry, data, account, match_currency: true)+ amount = data.dig(:transaction_amount, :amount).presence || data[:amount]+ return 0 if entry.nil? || amount.blank?++ signed = BigDecimal(amount.to_s).abs * (data[:credit_debit_indicator] == "CRDT" ? -1 : 1)+ currency = parse_currency(data.dig(:transaction_amount, :currency)) || parse_currency(data[:currency]) || account.currency+ return 0 unless entry.amount == signed && (!match_currency || entry.currency == currency)++ entry.date == transaction_date(data, account.family&.timezone) ? 2 : 1+ rescue ArgumentError, TypeError+ 0+ end+# True when the ASPSP supplied no identifier of its own, so compute_external_id# falls back to hashing the content.#@@ -235,9 +291,13 @@ class EnableBankingEntry::Processor# 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.+ #+ # 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)+ identifierless_external_ids: nil, excluded_external_ids: nil, external_id: nil)@enable_banking_transaction = enable_banking_transaction+ @external_id = external_id@enable_banking_account = enable_banking_account@import_adapter = import_adapter@known_merchant_names = known_merchant_names@@ -248,7 +308,7 @@ class EnableBankingEntry::Processordef process# Cache a safe diagnostic id upfront — used in all logging paths so rescue# blocks never call the potentially-raising private external_id method.- safe_id = self.class.compute_external_id(@enable_banking_transaction) || "unknown"+ safe_id = @external_id || self.class.compute_external_id(@enable_banking_transaction) || "unknown"unless account.present?Rails.logger.warn "EnableBankingEntry::Processor - No linked account for enable_banking_account #{enable_banking_account.id}, skipping transaction #{safe_id}"@@ -256,6 +316,7 @@ class EnableBankingEntry::Processorendclaim_identifierless_predecessor!+ skips = import_adapter.skipped_entries.size# EnableBankingAccount::Transactions::Processor re-processes the whole stored# payload on every sync, so a live hold passes through here once per sync until@@ -274,6 +335,7 @@ class EnableBankingEntry::Processorname: name,source: "enable_banking",merchant: merchant,+ allow_heuristic_matching: !plain_sibling_pending_match?,notes: notes,extra: extra,investment_activity_label: investment_activity_label@@ -290,6 +352,7 @@ class EnableBankingEntry::Processorraise StandardError.new("Unexpected error importing transaction: #{e.message}")end+ store_entry_reference(entry) if import_adapter.skipped_entries.size == skipscapture_unidentified_hold_diagnostic(entry, external_id: safe_id) if first_hold_import && entryentry@@ -312,11 +375,36 @@ class EnableBankingEntry::Processorenddef external_id- id = self.class.compute_external_id(data)+ id = @external_id || self.class.compute_external_id(data)raise ArgumentError, "Enable Banking transaction missing required identifier (transaction_id, entry_reference, or identifiable content)" unless ididend+ # A suffixed row must not claim, through the adapter's exact-amount pending match, the+ # pending entry still under its plain id. That entry belongs to the row keeping the plain+ # id, and stays pending when that row skips it as protected (excluded or import-locked).+ def plain_sibling_pending_match?+ plain_id = self.class.compute_external_id(data)+ return false if @external_id.nil? || @external_id == plain_id++ plain = account.entries.find_by(source: "enable_banking", external_id: plain_id)+ # The adapter tries a scheduled or manual duplicate before the pending match; keep those.+ plain&.entryable.try(:pending?) &&+ !import_adapter.find_scheduled_transaction(date: date, amount: amount, currency: currency) &&+ !import_adapter.find_duplicate_transaction(date: date, amount: amount, currency: currency) &&+ import_adapter.find_pending_transaction(date: date, amount: amount, currency: currency, source: "enable_banking") == plain+ end++ # external_ids_for reads the stored entry_reference to tell rows sharing a transaction_id+ # apart. It has its own column, so it is not part of the details rules match on. An entry+ # the adapter skipped as protected keeps what it had, as it keeps the rest of its data.+ def store_entry_reference(entry)+ reference = data[:entry_reference].to_s+ return if reference.blank? || data[:transaction_id].blank? || pending_payload? || !entry&.entryable.is_a?(Transaction)++ entry.transaction.update_column(:provider_entry_reference, reference) unless entry.transaction.provider_entry_reference == reference+ end+def namereturn HOLD_TRANSACTION_NAME if unidentified_hold?@@ -638,7 +726,7 @@ class EnableBankingEntry::Processor# sides avoids the two mechanisms fighting over the same row.return if pending_payload?- incoming = self.class.compute_external_id(data)+ 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))diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rbindex 8814b70945..de62d9e356 100644--- a/app/models/enable_banking_item/importer.rb+++ b/app/models/enable_banking_item/importer.rb@@ -978,14 +978,16 @@ class EnableBankingItem::Importerendend- existing_ids = existing_transactions.map { |tx|- EnableBankingEntry::Processor.compute_external_id(tx)- }.compact.to_set-- new_transactions = all_transactions.select do |tx|- ext_id = EnableBankingEntry::Processor.compute_external_id(tx)+ # Ids are computed over stored + fetched rows together so a fetched row+ # sharing a stored row's transaction_id, but not its entry_reference, is+ # recognised as new (see EnableBankingEntry::Processor.external_ids_for).+ ids = EnableBankingEntry::Processor.external_ids_for(existing_transactions + all_transactions)+ existing_ids = ids.first(existing_transactions.size).compact.to_set++ new_transactions = all_transactions.each_with_index.select { |_tx, index|+ ext_id = ids[existing_transactions.size + index]ext_id.present? && !existing_ids.include?(ext_id)- end+ }.map(&:first)if new_transactions.any? || removed_pendingenable_banking_account.upsert_enable_banking_transactions_snapshot!(existing_transactions + new_transactions)@@ -1011,16 +1013,20 @@ class EnableBankingItem::Importer{ success: false, transactions_count: 0, error: handle_sync_error(e) }end- # Deduplicate transactions from the Enable Banking API response.- # Some banks return the same logical transaction multiple times with different- # entry_reference IDs. We build a composite content key that includes- # transaction_id (when present) alongside date, amount, currency, creditor,- # debtor, remittance_information, and status. Per the Enable Banking API docs- # transaction_id is not guaranteed to be unique, so it cannot be used as- # the sole dedup criterion. Including it in the composite key preserves- # legitimately distinct transactions with identical content but different- # transaction_ids (e.g. two laundromat payments on the same day). (Issue #954)+ # Collapse rows the API returns more than once for the same movement.+ #+ # Two real same-day payments, with no transaction_id or a shared one (it is+ # not guaranteed unique), can match on every content field and differ only+ # in entry_reference, which Enable Banking documents as the per-account+ # identifier of a booked entry. Booked rows with distinct references+ # therefore stay apart, while pending and reference-less copies of the same+ # content still collapse into them.def deduplicate_api_transactions(transactions)+ reference_groups = transactions.each_with_object(Set.new) do |tx, groups|+ tx = tx.with_indifferent_access+ groups.add(build_transaction_content_key(tx)) if distinct_booked_reference?(tx)+ end+seen = {}duplicates_removed = 0@@ -1028,6 +1034,16 @@ class EnableBankingItem::Importertx = tx.with_indifferent_accesskey = build_transaction_content_key(tx)+ if reference_groups.include?(key)+ # Prefer booked rows over their otherwise identical pending/ID-less+ # copies, regardless of which appears first in the response.+ unless distinct_booked_reference?(tx)+ duplicates_removed += 1+ next false+ end+ key = [ key, tx[:entry_reference] ]+ end+if seen[key]duplicates_removed += 1false@@ -1047,9 +1063,12 @@ class EnableBankingItem::Importerresultend- # Build a composite key for deduplication. Two transactions with different- # entry_reference values but identical content fields (including- # transaction_id and credit_debit_indicator) are considered duplicates.+ def distinct_booked_reference?(tx)+ tx[:entry_reference].present? && !EnableBankingEntry::Processor.pending_payload?(tx)+ end++ # Build the content key for deduplication. Different entry_reference values+ # can share it; deduplicate_api_transactions decides whether they stay apart.# transaction_id is included as one component — not a standalone key —# because the Enable Banking API docs state it is not guaranteed to be# unique. credit_debit_indicator (CRDT/DBIT) is included because@@ -1057,12 +1076,9 @@ class EnableBankingItem::Importer# and a same-day refund of the same amount would produce identical keys.# status (BOOK/PDNG) is intentionally excluded: the same logical transaction# may appear as PDNG then BOOK across imports and must not create duplicates.- # Known limitation: when transaction_id is nil for both, pure content- # comparison applies. This means two genuinely distinct transactions- # with identical content (same date, amount, direction, creditor, etc.)- # and no transaction_id would collapse to one. In practice, banks that- # omit transaction_id rarely produce such exact duplicates in the same- # API response; timestamps or remittance info usually differ. (Issue #954)+ # Identical real operations share this key; their booked references tell+ # them apart (EnableBankingEntry::Processor.external_ids_for gives rows+ # sharing a transaction_id their own ids).def build_transaction_content_key(tx)date = tx[:booking_date].presence || tx[:value_date].presence || tx[:transaction_date]amount = tx.dig(:transaction_amount, :amount).presence || tx[:amount]diff --git a/db/migrate/20261114090000_add_provider_entry_reference_to_transactions.rb b/db/migrate/20261114090000_add_provider_entry_reference_to_transactions.rbnew file mode 100644index 0000000000..1c8fb56b83--- /dev/null+++ b/db/migrate/20261114090000_add_provider_entry_reference_to_transactions.rb@@ -0,0 +1,5 @@+class AddProviderEntryReferenceToTransactions < ActiveRecord::Migration[8.1]+ def change+ add_column :transactions, :provider_entry_reference, :string+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 3418d65708..81a8241677 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -2899,6 +2899,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_233000) dot.string "kind", default: "standard", null: falset.jsonb "locked_attributes", default: {}t.uuid "merchant_id"+ t.string "provider_entry_reference"t.uuid "transfer_id"t.datetime "updated_at", null: falset.index "(((extra -> 'goal'::text) ->> 'pledge_id'::text))", name: "ix_transactions_extra_goal_pledge_id", unique: true, where: "(((extra -> 'goal'::text) ->> 'pledge_id'::text) IS NOT NULL)"diff --git a/test/models/enable_banking_account/transactions/processor_test.rb b/test/models/enable_banking_account/transactions/processor_test.rbindex 2623e2673f..9644ebe30e 100644--- a/test/models/enable_banking_account/transactions/processor_test.rb+++ b/test/models/enable_banking_account/transactions/processor_test.rb@@ -371,4 +371,458 @@ class EnableBankingAccount::Transactions::ProcessorTest < ActiveSupport::TestCasassert_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)+ endenddiff --git a/test/models/enable_banking_entry/processor_test.rb b/test/models/enable_banking_entry/processor_test.rbindex 7d939565cc..ba087d736e 100644--- a/test/models/enable_banking_entry/processor_test.rb+++ b/test/models/enable_banking_entry/processor_test.rb@@ -1601,4 +1601,17 @@ class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCaseassert_not_nil resultassert_equal Date.new(2025, 7, 15), result.dateend++ test "external_ids_for leaves rows without a shared transaction_id on compute_external_id" do+ rows = [+ { entry_reference: "ref-1", booking_date: "2026-03-05", transaction_amount: { amount: "1.00", currency: "EUR" } },+ { booking_date: "2026-03-05", transaction_amount: { amount: "2.00", currency: "EUR" }, remittance_information: [ "X" ] },+ { transaction_id: "tid-y", entry_reference: "ref-2", booking_date: "2026-03-05", transaction_amount: { amount: "3.00", currency: "EUR" } },+ { transaction_id: "tid-z", booking_date: "2026-03-05", transaction_amount: { amount: "4.00", currency: "EUR" } },+ { transaction_id: "tid-z", booking_date: "2026-03-05", transaction_amount: { amount: "5.00", currency: "EUR" } }+ ]++ assert_equal rows.map { |r| EnableBankingEntry::Processor.compute_external_id(r) },+ EnableBankingEntry::Processor.external_ids_for(rows)+ endenddiff --git a/test/models/enable_banking_item/importer_dedup_test.rb b/test/models/enable_banking_item/importer_dedup_test.rbindex af6737a1ac..a565213c49 100644--- a/test/models/enable_banking_item/importer_dedup_test.rb+++ b/test/models/enable_banking_item/importer_dedup_test.rb@@ -17,7 +17,7 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCase@importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: mock_provider)end- test "removes content-level duplicates with different entry_reference IDs" do+ test "keeps booked transactions that differ only in entry_reference" dotransactions = [{entry_reference: "ref_aaa",@@ -41,8 +41,7 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCaseresult = @importer.send(:deduplicate_api_transactions, transactions)- assert_equal 1, result.count- assert_equal "ref_aaa", result.first[:entry_reference]+ assert_equal %w[ref_aaa ref_bbb], result.map { |tx| tx[:entry_reference] }endtest "keeps transactions with different amounts" do@@ -124,8 +123,8 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCasetransactions = [base.merge(entry_reference: "ref_1"),- base.merge(entry_reference: "ref_2"),- base.merge(entry_reference: "ref_3")+ base.merge(entry_reference: "ref_1"),+ base.merge(entry_reference: nil)]result = @importer.send(:deduplicate_api_transactions, transactions)@@ -136,6 +135,13 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCasetest "handles string keys in transaction data" dotransactions = [+ {+ "entry_reference" => "ref_aaa",+ "booking_date" => "2026-02-07",+ "transaction_amount" => { "amount" => "11.65", "currency" => "EUR" },+ "creditor" => { "name" => "Spar" },+ "status" => "BOOK"+ },{"entry_reference" => "ref_aaa","booking_date" => "2026-02-07",@@ -154,7 +160,7 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCaseresult = @importer.send(:deduplicate_api_transactions, transactions)- assert_equal 1, result.count+ assert_equal %w[ref_aaa ref_bbb], result.map { |tx| tx["entry_reference"] }endtest "differentiates by remittance_information" do@@ -193,7 +199,7 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCasestatus: "BOOK"},{- entry_reference: "ref_bbb",+ entry_reference: "ref_aaa",booking_date: "2026-02-07",transaction_amount: { amount: "11.65", currency: "EUR" },creditor: { name: "Spar" },@@ -233,7 +239,7 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCaseassert_equal 2, result.countend- test "deduplicates same transaction_id even with different entry_references" do+ test "keeps booked rows sharing a transaction_id that differ only in entry_reference" dotransactions = [{entry_reference: "ref_aaa",@@ -255,8 +261,7 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCaseresult = @importer.send(:deduplicate_api_transactions, transactions)- assert_equal 1, result.count- assert_equal "ref_aaa", result.first[:entry_reference]+ assert_equal %w[ref_aaa ref_bbb], result.map { |tx| tx[:entry_reference] }endtest "preserves transactions with same non-unique transaction_id but different content" do@@ -297,7 +302,7 @@ class EnableBankingItem::ImporterDedupTest < ActiveSupport::TestCasestatus: "BOOK"},{- entry_reference: "ref_2",+ entry_reference: "ref_1",transaction_id: nil,value_date: "2026-02-10",transaction_amount: { amount: "1.50", currency: "EUR" },diff --git a/test/models/enable_banking_item/importer_shared_transaction_id_test.rb b/test/models/enable_banking_item/importer_shared_transaction_id_test.rbnew file mode 100644index 0000000000..b015c377d3--- /dev/null+++ b/test/models/enable_banking_item/importer_shared_transaction_id_test.rb@@ -0,0 +1,144 @@+require "test_helper"++# Enable Banking does not guarantee transaction_id to be unique. Rows that share+# one but carry different entry_references must stay separate entries, across+# syncs, without changing the id of an entry that already exists.+class EnableBankingItem::ImporterSharedTransactionIdTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @account = accounts(:depository)++ @enable_banking_item = EnableBankingItem.create!(+ family: @family,+ name: "Test EB",+ country_code: "FR",+ application_id: "test_app_id",+ client_certificate: "test_cert",+ session_id: "test_session",+ session_expires_at: 1.day.from_now,+ sync_start_date: Date.new(2026, 3, 1)+ )+ @enable_banking_account = EnableBankingAccount.create!(+ enable_banking_item: @enable_banking_item,+ name: "Compte courant",+ uid: "hash_shared_tid",+ account_id: "uuid-shared-tid",+ currency: "EUR"+ )+ AccountProvider.create!(account: @account, provider: @enable_banking_account)++ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: mock())+ @importer.stubs(:include_pending?).returns(false)+ end++ test "a sibling row arriving in a later sync is stored and imported as its own entry" do+ sync(booked: [ row("r-a", "9.00") ])+ legacy = entry!("enable_banking_tid-x")++ sync(booked: [ row("r-b", "7.00"), row("r-a", "9.00") ])++ assert_equal [ "r-a", "r-b" ], stored_refs+ assert_equal({ "enable_banking_tid-x" => BigDecimal("9.00"), sibling_id("r-b") => BigDecimal("7.00") }, amounts_by_id)+ assert_equal legacy.id, entry!("enable_banking_tid-x").id+ end++ test "re-fetching the rows in reverse order creates no entries and swaps no ids" do+ sync(booked: [ row("r-a", "9.00"), row("r-b", "7.00") ])+ before = @account.entries.where(source: "enable_banking").pluck(:id, :external_id, :amount).sort++ sync(booked: [ row("r-b", "7.00"), row("r-a", "9.00") ])++ assert_equal [ "r-a", "r-b" ], stored_refs+ assert_equal before, @account.entries.where(source: "enable_banking").pluck(:id, :external_id, :amount).sort+ end++ test "a pending row still settles into the entry under the legacy id" do+ @importer.stubs(:include_pending?).returns(true)++ sync(booked: [], pending: [ row("r-p", "9.00", status: "PDNG") ])+ pending_entry = entry!("enable_banking_tid-x")+ assert pending_entry.transaction.pending?++ sync(booked: [ row("r-a", "9.00"), row("r-b", "7.00") ], pending: [])++ assert_equal [ "r-a", "r-b" ], stored_refs+ assert_equal 2, @account.entries.where(source: "enable_banking").count+ assert_equal pending_entry.id, entry!("enable_banking_tid-x").id+ assert_not pending_entry.reload.transaction.pending?+ assert_equal BigDecimal("7.00"), entry!(sibling_id("r-b")).amount+ end++ test "a pending entry stays with its booked row when a same-amount sibling comes first" do+ @importer.stubs(:include_pending?).returns(true)+ sync(booked: [], pending: [ row("r-p", "7.00", status: "PDNG", date: 3.days.ago.to_date) ])+ pending_entry = entry!("enable_banking_tid-x")+ pending_entry.update!(notes: "dinner")++ sync(booked: [ row("r-a", "7.00", date: 2.days.ago.to_date), row("r-b", "7.00", date: 3.days.ago.to_date) ], pending: [])++ assert_equal [ [ "enable_banking_tid-x", 3.days.ago.to_date, "dinner" ], [ sibling_id("r-a"), 2.days.ago.to_date, nil ] ],+ @account.entries.where(source: "enable_banking").order(:external_id).pluck(:external_id, :date, :notes)+ assert_not pending_entry.reload.transaction.pending?+ end++ test "a pending entry settles onto the booked sibling with its amount when the dates differ" do+ @importer.stubs(:include_pending?).returns(true)+ sync(booked: [], pending: [ row("r-p", "7.00", status: "PDNG", date: 5.days.ago.to_date) ])+ pending_entry = entry!("enable_banking_tid-x")++ sync(booked: [ row("r-a", "9.00"), row("r-b", "7.00") ], pending: [])++ assert_equal({ "enable_banking_tid-x" => BigDecimal("7.00"), sibling_id("r-a") => BigDecimal("9.00") }, amounts_by_id)+ assert_equal pending_entry.id, entry!("enable_banking_tid-x").id+ end++ test "two booked rows returned together with identical content and distinct references import as two entries" do+ sync(booked: [ row("r-a", "7.00"), row("r-b", "7.00") ])++ assert_equal [ "r-a", "r-b" ], stored_refs+ assert_equal({ "enable_banking_tid-x" => BigDecimal("7.00"), sibling_id("r-b") => BigDecimal("7.00") }, amounts_by_id)+ end++ private++ # date: inside the 30-day incremental window determine_sync_start_date uses.+ def row(entry_reference, amount, status: "BOOK", date: 3.days.ago.to_date)+ {+ transaction_id: "tid-x",+ entry_reference: entry_reference,+ booking_date: date.to_s,+ transaction_amount: { amount: amount, currency: "EUR" },+ creditor: { name: "Laundromat" },+ credit_debit_indicator: "DBIT",+ status: status+ }+ end++ def sync(booked:, pending: nil)+ @importer.stubs(:fetch_paginated_transactions)+ .with(@enable_banking_account, has_entries(transaction_status: "BOOK")).returns(booked)+ unless pending.nil?+ @importer.stubs(:fetch_paginated_transactions)+ .with(@enable_banking_account, has_entries(transaction_status: "PDNG")).returns(pending)+ end++ assert @importer.send(:fetch_and_store_transactions, @enable_banking_account)[:success]+ EnableBankingAccount::Transactions::Processor.new(@enable_banking_account.reload).process+ end++ def sibling_id(entry_reference)+ "enable_banking_tid-x_#{Digest::MD5.hexdigest(entry_reference)}"+ end++ def stored_refs+ @enable_banking_account.reload.raw_transactions_payload.map { |tx| tx.with_indifferent_access[:entry_reference] }+ end++ def entry!(external_id)+ @account.entries.find_by!(source: "enable_banking", external_id: external_id)+ end++ def amounts_by_id+ @account.entries.where(source: "enable_banking").pluck(:external_id, :amount).to_h+ end+end