Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Revert "fix(enable_banking): tell id-less rows that share a content hash apar…"

Juan José Mataeb34c06f0e90
diff --git a/app/models/enable_banking_account/transactions/processor.rb b/app/models/enable_banking_account/transactions/processor.rb
index eed4d8377c..efa525d0a2 100644
--- a/app/models/enable_banking_account/transactions/processor.rb
+++ b/app/models/enable_banking_account/transactions/processor.rb
@@ -1,5 +1,3 @@
-require "digest/md5"
-
class EnableBankingAccount::Transactions::Processor
attr_reader :enable_banking_account
@@ -79,15 +77,9 @@ class EnableBankingAccount::Transactions::Processor
Set.new
end
- # A row without a provider id hashes to its content, and within one response
- # two such rows can share that hash. Each such row gets a suffix that tells
- # it apart, worked out over the whole batch before any row is imported.
- identities = content_identities(enable_banking_account.raw_transactions_payload, excluded_ids)
-
enable_banking_account.raw_transactions_payload.each_with_index do |transaction_data, index|
begin
- id_suffix, fingerprint = identities[index]
- ext_id = EnableBankingEntry::Processor.compute_external_id(transaction_data, suffix: id_suffix)
+ ext_id = EnableBankingEntry::Processor.compute_external_id(transaction_data)
if ext_id && excluded_ids.include?(ext_id)
Rails.logger.info("EnableBankingAccount::Transactions::Processor - Skipping re-import of manually merged pending transaction: #{ext_id}")
@@ -99,9 +91,7 @@ class EnableBankingAccount::Transactions::Processor
transaction_data,
enable_banking_account: enable_banking_account,
import_adapter: shared_adapter,
- known_merchant_names: shared_known_merchant_names,
- id_suffix: id_suffix,
- content_fingerprint: fingerprint
+ known_merchant_names: shared_known_merchant_names
).process
if result.nil?
@@ -143,125 +133,4 @@ class EnableBankingAccount::Transactions::Processor
result
end
-
- private
-
- # For each row, [suffix, fingerprint]: the suffix that tells an id-less row
- # apart from the other rows of the batch that hash to the same content (nil
- # when none is needed), and the full-content fingerprint recorded on it.
- # [nil, nil] for a row with a provider id or with nothing to hash.
- #
- # A suffix has to be an identity, not a position: the next response may
- # order the rows differently, carry only one of them, or add a third. So
- # the identities a group already has -- in the ledger, or among the ids
- # excluded because they were merged away -- are resolved first, and only
- # what is left is given a new one:
- #
- # - a member whose full-content id is already known keeps it;
- # - a bare-form id already known (the hash alone, or numbered) goes to the
- # member whose recorded fingerprint it carries; when the entry is older
- # than fingerprints, to the only member, or to any of a set of identical
- # members, which are interchangeable; if that cannot be told, it is left
- # alone, and the row imports under its own id -- one visible duplicate
- # rather than a silent update of the wrong transaction;
- # - the rest: rows identical in every field are numbered from the bare hash,
- # the first keeping it bare; rows that differ in a field the hash does not
- # read each take a hash of their full content.
- def content_identities(rows, excluded_ids)
- bases = rows.map { |row| EnableBankingEntry::Processor.compute_external_id(row) rescue nil }
- fulls = rows.map { |row| EnableBankingEntry::Processor.content_fingerprint(row) }
-
- groups = Hash.new { |h, k| h[k] = [] }
- bases.each_with_index { |base, i| groups[base] << i if base&.start_with?("enable_banking_content_") }
- return Array.new(rows.size) { [ nil, nil ] } if groups.empty?
-
- known = known_identities(groups.keys)
- excluded = excluded_ids.to_set
-
- ids = {}
- ambiguous = []
- groups.each do |base, members|
- ranks = {}
- members.sort_by { |i| [ fulls[i], i ] }.group_by { |i| fulls[i] }.each_value do |same|
- same.each_with_index { |i, rank| ranks[i] = rank }
- end
- full_id = ->(i) { ranks[i].zero? ? "#{base}_#{fulls[i]}" : "#{base}_#{fulls[i]}_#{ranks[i]}" }
- bare_id = ->(i) { ranks[i].zero? ? base : "#{base}_#{ranks[i]}" }
- taken = ->(id) { known.key?(id) || excluded.include?(id) }
-
- # 1. Full-content identities already known.
- members.each { |i| ids[i] = full_id.call(i) if taken.call(full_id.call(i)) }
-
- # 2. Bare-form identities already known, claimed by fingerprint or when unambiguous.
- members.reject { |i| ids.key?(i) }.group_by { |i| bare_id.call(i) }.each do |id, holders|
- next unless taken.call(id)
- next if ids.value?(id)
-
- fingerprint = known[id]
- owner = if fingerprint.present?
- holders.find { |i| fulls[i] == fingerprint }
- elsif holders.map { |i| fulls[i] }.uniq.size == 1
- holders.first
- end
- ids[owner] = id if owner
- ambiguous << id if owner.nil? && fingerprint.blank?
- end
-
- # 3. New identities for what is left, by the shape of the group. A bare
- # id that is already taken, and was not claimed above, belongs to a
- # different row; the newcomer takes its own full-content id instead
- # of overwriting that transaction, or of being skipped as it.
- remaining = members.reject { |i| ids.key?(i) }
- identical = members.map { |i| fulls[i] }.uniq.size == 1
- remaining.each do |i|
- candidate = identical || members.size == 1 ? bare_id.call(i) : full_id.call(i)
- candidate = full_id.call(i) if candidate == bare_id.call(i) && (taken.call(candidate) || ids.value?(candidate))
- ids[i] = candidate
- end
- end
-
- report_ambiguous_identities(ambiguous) if ambiguous.any?
-
- rows.each_index.map do |i|
- next [ nil, nil ] unless ids.key?(i)
-
- id = ids[i]
- suffix = id == bases[i] ? nil : id.delete_prefix("#{bases[i]}_")
- [ suffix, fulls[i] ]
- end
- end
-
- # An entry from before fingerprints were recorded, whose content hash is now
- # shared by rows that differ: which of them it was made from cannot be
- # told, so it is left as it is and the rows import under their own ids.
- # That leaves the account one visible duplicate, which support may be asked
- # about, so it is recorded.
- def report_ambiguous_identities(external_ids)
- DebugLogEntry.capture(
- category: "provider_sync",
- level: "warn",
- message: "Enable Banking id-less entry could not be matched to one of several rows sharing its content hash; " \
- "kept as is, and the rows were imported under their own ids",
- source: self.class.name,
- provider_key: "enable_banking",
- account_provider: enable_banking_account.account_provider,
- family: enable_banking_account.enable_banking_item&.family,
- metadata: { external_ids: external_ids }
- )
- end
-
- # The ids the ledger already holds for these content hashes, bare or
- # suffixed, with the fingerprint recorded on each where there is one.
- def known_identities(bases)
- account = enable_banking_account.current_account
- return {} unless account
-
- patterns = bases.map { |base| "#{base.gsub(/[\\%_]/) { |c| "\\#{c}" }}\\_%" }
- account.entries
- .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
- .where(source: "enable_banking")
- .where("entries.external_id = ANY(ARRAY[?]::text[]) OR entries.external_id LIKE ANY(ARRAY[?]::text[])", bases, patterns)
- .pluck(:external_id, Arel.sql("transactions.extra -> 'enable_banking' ->> 'content_fingerprint'"))
- .to_h
- end
end
diff --git a/app/models/enable_banking_entry/processor.rb b/app/models/enable_banking_entry/processor.rb
index 9314a9b07a..cf0922b283 100644
--- a/app/models/enable_banking_entry/processor.rb
+++ b/app/models/enable_banking_entry/processor.rb
@@ -30,16 +30,8 @@ class EnableBankingEntry::Processor
# transaction_amount: { amount, currency },
# creditor_name, debtor_name, remittance_information, ...
# }
- #
- # suffix: set by the batch processor for an id-less row that shares its
- # content hash with another row of the same response. Some ASPSPs send none
- # of the fields below but date, amount, currency and direction, so two
- # transfers of the same amount on the same day are one hash, and the second
- # silently updated the first. A row without a suffix hashes exactly as
- # before, so rows already imported keep their ids; a row carrying a provider
- # id never needs one.
- def self.compute_external_id(raw_transaction_data = nil, suffix: nil, **row_keywords)
- data = (raw_transaction_data || row_keywords).with_indifferent_access
+ def self.compute_external_id(raw_transaction_data)
+ data = raw_transaction_data.with_indifferent_access
id = data[:transaction_id].presence || data[:entry_reference].presence
return "enable_banking_#{id}" if id
@@ -59,25 +51,7 @@ class EnableBankingEntry::Processor
content = [ date, amount, currency, direction, creditor, debtor, remittance_key ].map(&:to_s).join("\x1F")
return nil if content.gsub("\x1F", "").blank?
- id = "enable_banking_content_#{Digest::MD5.hexdigest(content)}"
- suffix.present? ? "#{id}_#{suffix}" : id
- end
-
- # A digest of the whole row, every field, keys sorted: what tells apart two
- # rows that share the hashed fields above. Recorded on the imported
- # transaction so a later batch can tell which row an entry was made from.
- def self.content_fingerprint(raw_transaction_data)
- Digest::MD5.hexdigest(JSON.generate(deep_sort(raw_transaction_data)))
- rescue StandardError
- Digest::MD5.hexdigest(raw_transaction_data.to_s)
- end
-
- def self.deep_sort(value)
- case value
- when Hash then value.map { |k, v| [ k.to_s, deep_sort(v) ] }.sort.to_h
- when Array then value.map { |v| deep_sort(v) }
- else value
- end
+ "enable_banking_content_#{Digest::MD5.hexdigest(content)}"
end
# known_merchant_names: optional pre-fetched Family#known_merchant_names, so a
@@ -85,25 +59,17 @@ 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).
- #
- # id_suffix: see compute_external_id; the batch processor works it out over
- # the whole response and passes each row its own.
- # content_fingerprint: recorded in extra for an id-less row (see
- # content_fingerprint above), so the row an entry was made from can be told
- # later; nil for a row that carries a provider id.
- def initialize(enable_banking_transaction, enable_banking_account:, import_adapter: nil, known_merchant_names: nil, id_suffix: nil, content_fingerprint: nil)
+ def initialize(enable_banking_transaction, enable_banking_account:, import_adapter: nil, known_merchant_names: nil)
@enable_banking_transaction = enable_banking_transaction
@enable_banking_account = enable_banking_account
@import_adapter = import_adapter
@known_merchant_names = known_merchant_names
- @id_suffix = id_suffix
- @content_fingerprint = content_fingerprint
end
def 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, suffix: @id_suffix) || "unknown"
+ safe_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}"
@@ -152,7 +118,7 @@ class EnableBankingEntry::Processor
end
def external_id
- id = self.class.compute_external_id(data, suffix: @id_suffix)
+ id = self.class.compute_external_id(data)
raise ArgumentError, "Enable Banking transaction missing required identifier (transaction_id, entry_reference, or identifiable content)" unless id
id
end
@@ -229,7 +195,6 @@ class EnableBankingEntry::Processor
eb[:merchant_category_code] = data[:merchant_category_code] if data[:merchant_category_code].present?
eb[:pending] = true if data[:_pending] == true
- eb[:content_fingerprint] = @content_fingerprint if @content_fingerprint.present?
eb.compact!
eb.empty? ? nil : { enable_banking: eb }
@@ -378,7 +343,7 @@ class EnableBankingEntry::Processor
end
def log_invalid_currency(currency_value)
- safe_id = self.class.compute_external_id(data, suffix: @id_suffix) || "unknown"
+ safe_id = self.class.compute_external_id(data) || "unknown"
Rails.logger.warn("Invalid currency code '#{currency_value}' in Enable Banking transaction #{safe_id}, falling back to account currency")
end
diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rb
index 535c2751d1..a008e44635 100644
--- a/app/models/enable_banking_item/importer.rb
+++ b/app/models/enable_banking_item/importer.rb
@@ -454,7 +454,6 @@ class EnableBankingItem::Importer
end
def fetch_and_store_transactions(enable_banking_account)
- @truncated_statuses = Set.new
start_date = determine_sync_start_date(enable_banking_account)
include_pending = include_pending?
@@ -580,7 +579,14 @@ class EnableBankingItem::Importer
end
end
- new_transactions = select_new_transactions(all_transactions, existing_transactions, truncated_statuses: @truncated_statuses)
+ 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)
+ ext_id.present? && !existing_ids.include?(ext_id)
+ end
if new_transactions.any? || removed_pending
enable_banking_account.upsert_enable_banking_transactions_snapshot!(existing_transactions + new_transactions)
@@ -609,21 +615,12 @@ class EnableBankingItem::Importer
# 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)
- #
- # A row with neither transaction_id nor entry_reference is left alone. The
- # duplicates this guards against carry different entry_references; two
- # bare rows with the same content are, as far as the response can say, two
- # transactions -- an ASPSP that sends only date, amount, currency and
- # direction reports two same-day transfers of the same amount exactly that
- # way, and collapsing them here lost one.
def deduplicate_api_transactions(transactions)
seen = {}
duplicates_removed = 0
result = transactions.select do |tx|
tx = tx.with_indifferent_access
- next true if bare_transaction?(tx)
-
key = build_transaction_content_key(tx)
if seen[key]
@@ -675,87 +672,6 @@ class EnableBankingItem::Importer
[ date, amount, currency, creditor, debtor, remittance_key, tid, direction ].map(&:to_s).join("\x1F")
end
- def bare_transaction?(tx)
- tx[:transaction_id].blank? && tx[:entry_reference].blank?
- end
-
- # The fetched rows not yet in the stored payload. A row with a provider id
- # is new when its id is not stored, as before. Id-less rows are compared
- # per content hash, matching full contents against the stored ones:
- #
- # - a complete response covers whole dates, and the hash includes the date,
- # so a group is new by however many rows it grew. Among the fetched rows,
- # those whose full content is not stored yet are the ones taken; a row
- # whose unhashed fields merely changed has not grown the group and is
- # not stored twice.
- # - a truncated response may leave stored rows out, so the group's size
- # says nothing. Every fetched row whose full content is not stored is
- # taken: at worst an edited row is stored twice, a visible duplicate,
- # where counting would silently lose a new one.
- #
- # Booked and pending rows come from separate fetches, either of which can
- # be cut short, so the two are compared apart, each by its own fetch's
- # completeness.
- def select_new_transactions(fetched, stored, truncated_statuses: Set.new)
- stored_ids = Set.new
- stored_groups = Hash.new { |h, k| h[k] = [] }
- stored.each do |tx|
- id = EnableBankingEntry::Processor.compute_external_id(tx)
- next if id.blank?
-
- if id.start_with?("enable_banking_content_")
- stored_groups[[ id, row_status(tx) ]] << EnableBankingEntry::Processor.content_fingerprint(comparable_row(tx))
- else
- stored_ids << id
- end
- end
-
- fetched_groups = Hash.new { |h, k| h[k] = [] }
- selected = []
- fetched.each do |tx|
- id = EnableBankingEntry::Processor.compute_external_id(tx)
- next if id.blank?
-
- if id.start_with?("enable_banking_content_")
- fetched_groups[[ id, row_status(tx) ]] << tx
- elsif !stored_ids.include?(id)
- selected << tx
- end
- end
-
- fetched_groups.each do |(id, status), rows|
- stored_fingerprints = stored_groups[[ id, status ]]
- unmatched = stored_fingerprints.tally
- fresh = rows.reject do |tx|
- fingerprint = EnableBankingEntry::Processor.content_fingerprint(comparable_row(tx))
- next false unless unmatched[fingerprint].to_i.positive?
-
- unmatched[fingerprint] -= 1
- true
- end
-
- if truncated_statuses.include?(status)
- selected.concat(fresh)
- else
- missing = rows.size - stored_fingerprints.size
- selected.concat((fresh + rows).uniq(&:object_id).first(missing)) if missing.positive?
- end
- end
-
- selected
- end
-
- def row_status(tx)
- tx = tx.with_indifferent_access
- tx[:_pending] || tx.dig(:extra, :enable_banking, :pending) ? "PDNG" : "BOOK"
- end
-
- # A stored row and a fetched one are the same row whatever the pending tag
- # or the key style says.
- def comparable_row(tx)
- tx.to_h.deep_stringify_keys.except("_pending")
- end
-
class PaginationTruncatedError < StandardError; end
def fetch_paginated_transactions(enable_banking_account, start_date:, transaction_status:, psu_headers: {})
@@ -810,7 +726,6 @@ class EnableBankingItem::Importer
transactions_kept: all_transactions.count,
error: e
)
- (@truncated_statuses ||= Set.new) << transaction_status
break
end
@@ -833,7 +748,6 @@ class EnableBankingItem::Importer
# Log as warning and return collected partial data instead of failing entirely.
# This ensures accounts with huge history don't lose all synced data.
Rails.logger.warn(e.message)
- (@truncated_statuses ||= Set.new) << transaction_status
all_transactions
end
diff --git a/test/models/enable_banking_account/transactions/processor_test.rb b/test/models/enable_banking_account/transactions/processor_test.rb
index 5b9ca1ce04..81426dce3c 100644
--- a/test/models/enable_banking_account/transactions/processor_test.rb
+++ b/test/models/enable_banking_account/transactions/processor_test.rb
@@ -24,17 +24,6 @@ class EnableBankingAccount::Transactions::ProcessorTest < ActiveSupport::TestCas
AccountProvider.create!(account: @account, provider: @enable_banking_account)
end
- # Two id-less rows that share every hashed field and differ only in a note.
- def distinguishable_collision_rows
- base = {
- "booking_date" => Date.current.to_s,
- "transaction_amount" => { "amount" => "100.00", "currency" => "EUR" },
- "credit_debit_indicator" => "CRDT",
- "status" => "BOOK"
- }
- [ base.merge("note" => "first transfer"), base.merge("note" => "second transfer") ]
- end
-
# Minimal raw transaction payload hash matching the shape EnableBankingEntry::Processor expects
def raw_pending_transaction(transaction_id:)
{
@@ -185,178 +174,6 @@ class EnableBankingAccount::Transactions::ProcessorTest < ActiveSupport::TestCas
assert @account.entries.exists?(external_id: expected_id, source: "enable_banking")
end
- # An ASPSP that sends only date, amount, currency and direction makes two
- # same-day transfers of the same amount one content hash; the second used to
- # update the first and the account silently lost a transaction.
- test "imports two identical id-less rows from one batch as two transactions, once" do
- tx = {
- "booking_date" => Date.current.to_s,
- "transaction_amount" => { "amount" => "100.00", "currency" => "EUR" },
- "credit_debit_indicator" => "CRDT",
- "status" => "BOOK"
- }
- @enable_banking_account.update!(raw_transactions_payload: [ tx, tx.dup ])
-
- assert_difference "@account.entries.count", 2 do
- result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- assert_equal 2, result[:imported]
- assert_equal 0, result[:failed]
- end
-
- # The same response again adds nothing: both rows keep the ids they were given.
- assert_no_difference "@account.entries.count" do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
-
- ids = @account.entries.where(source: "enable_banking").pluck(:external_id)
- assert_includes ids, EnableBankingEntry::Processor.compute_external_id(tx), "the first keeps the bare hash"
- assert_includes ids, EnableBankingEntry::Processor.compute_external_id(tx, suffix: "1")
- end
-
- # Two rows can collide on every hashed field and still differ in one the hash
- # does not read. Each takes an id from its full content, so the next response
- # can order them as it likes.
- test "collision rows that differ in an unhashed field keep their identity when the response is reordered" do
- first, second = distinguishable_collision_rows
-
- @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
- assert_difference "@account.entries.count", 2 do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
- before = @account.entries.where(source: "enable_banking").to_h { |e| [ e.external_id, e.notes ] }
- assert_equal 2, before.size
- assert_equal [ "first transfer", "second transfer" ], before.values.sort
-
- @enable_banking_account.update!(raw_transactions_payload: [ second, first ])
- assert_no_difference "@account.entries.count" do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
- after = @account.entries.where(source: "enable_banking").to_h { |e| [ e.external_id, e.notes ] }
- assert_equal before, after, "each row must keep the id it had, and so its note"
- end
-
- # A row once seen beside a twin may arrive alone in a later response. It is a
- # singleton then, but its full-content id is already in the ledger, so it
- # keeps that rather than taking the bare hash and becoming its twin.
- test "a collision row that later arrives alone keeps its identity" do
- first, second = distinguishable_collision_rows
-
- @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- second_id = @account.entries.where(source: "enable_banking").find_by(notes: "second transfer").external_id
-
- @enable_banking_account.update!(raw_transactions_payload: [ second ])
- assert_no_difference "@account.entries.count" do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
-
- assert_equal second_id, @account.entries.where(source: "enable_banking").find_by(notes: "second transfer").external_id
- assert_equal "first transfer", @account.entries.where(source: "enable_banking").where.not(external_id: second_id).first.notes, "the first is untouched"
- end
-
- # Resolving identities before assigning them: the ledger says which member a
- # bare entry was made from, so a row first seen alone and later beside a
- # distinguishable twin keeps its id, and only the twin is new.
- test "a row first imported alone keeps its id when a distinguishable twin arrives" do
- first, second = distinguishable_collision_rows
-
- @enable_banking_account.update!(raw_transactions_payload: [ first ])
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- first_id = @account.entries.where(source: "enable_banking").sole.external_id
- assert_equal EnableBankingEntry::Processor.compute_external_id(first), first_id, "alone, it carries the bare hash"
-
- @enable_banking_account.update!(raw_transactions_payload: [ second, first ])
- assert_difference "@account.entries.count", 1 do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
-
- by_note = @account.entries.where(source: "enable_banking").to_h { |e| [ e.notes, e.external_id ] }
- assert_equal first_id, by_note["first transfer"], "the first keeps the id it had"
- assert_not_equal first_id, by_note["second transfer"]
- end
-
- # The reverse transition: a group that was distinguishable is identical-only
- # next time. Its members still carry the ids they were given.
- test "members keep their ids when the group's shape changes between batches" do
- first, second = distinguishable_collision_rows
-
- @enable_banking_account.update!(raw_transactions_payload: [ first, first.dup, second ])
- assert_difference "@account.entries.count", 3 do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
- before = @account.entries.where(source: "enable_banking").pluck(:external_id).sort
-
- @enable_banking_account.update!(raw_transactions_payload: [ first, first.dup ])
- assert_no_difference "@account.entries.count" do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
- assert_equal before, @account.entries.where(source: "enable_banking").pluck(:external_id).sort
- end
-
- # A collision row the user merged away is excluded by its id. Arriving alone
- # later it must still be recognised as that id, or it comes back.
- test "a merged collision row that later arrives alone is still excluded" do
- first, second = distinguishable_collision_rows
-
- @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- second_entry = @account.entries.where(source: "enable_banking").find_by(notes: "second transfer")
- second_id = second_entry.external_id
-
- # As merge_with_duplicate! leaves things: the merged entry is gone, and the
- # survivor records where it came from.
- survivor = @account.entries.where(source: "enable_banking").find_by(notes: "first transfer")
- survivor.transaction.update!(extra: { "manual_merge" => { "merged_from_external_id" => second_id, "merged_at" => Time.current.iso8601, "source" => "enable_banking" } })
- second_entry.destroy!
-
- @enable_banking_account.update!(raw_transactions_payload: [ second ])
- assert_no_difference "@account.entries.count" do
- result = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- assert_equal 1, result[:skipped]
- end
- end
-
- # A bare id already in the ledger with another row's fingerprint belongs to
- # that row. A newcomer arriving alone must not take it and overwrite it.
- test "a distinguishable row arriving alone does not overwrite the row that holds the bare id" do
- first, second = distinguishable_collision_rows
-
- @enable_banking_account.update!(raw_transactions_payload: [ first ])
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- first_entry = @account.entries.where(source: "enable_banking").sole
-
- @enable_banking_account.update!(raw_transactions_payload: [ second ])
- assert_difference "@account.entries.count", 1 do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
-
- assert_equal "first transfer", first_entry.reload.notes, "the first keeps its own data"
- second_entry = @account.entries.where(source: "enable_banking").find_by(notes: "second transfer")
- assert second_entry
- assert_not_equal first_entry.external_id, second_entry.external_id
- assert second_entry.external_id.start_with?("#{first_entry.external_id}_")
- end
-
- # An entry from before fingerprints were recorded, now shared by two rows
- # that differ: it cannot be told which it was, so it is kept and the case
- # is put where support can see it.
- test "records an ambiguous legacy entry in the debug log and leaves it alone" do
- first, second = distinguishable_collision_rows
- legacy = @account.entries.create!(
- date: Date.current, name: "Legacy", amount: -100, currency: "EUR",
- external_id: EnableBankingEntry::Processor.compute_external_id(first), source: "enable_banking",
- entryable: Transaction.new
- )
-
- @enable_banking_account.update!(raw_transactions_payload: [ first, second ])
- assert_difference "DebugLogEntry.where(level: \"warn\", provider_key: \"enable_banking\").count", 1 do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
-
- assert_equal "Legacy", legacy.reload.name, "the legacy entry is not overwritten"
- assert_equal 3, @account.entries.where(source: "enable_banking").count
- end
-
test "id-less transaction does not appear in failed count" do
tx = {
"booking_date" => Date.current.to_s,
diff --git a/test/models/enable_banking_entry/processor_test.rb b/test/models/enable_banking_entry/processor_test.rb
index c949281d8b..7ad51044c6 100644
--- a/test/models/enable_banking_entry/processor_test.rb
+++ b/test/models/enable_banking_entry/processor_test.rb
@@ -118,39 +118,6 @@ class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCase
EnableBankingEntry::Processor.compute_external_id(tx)
end
- # Some ASPSPs send only date, amount, currency and direction; two transfers of
- # the same amount on one day then hash alike, and the second overwrote the
- # first. The batch processor hands a repeat a suffix; the first hashes as before.
- test "compute_external_id appends the suffix the batch processor gives a repeated id-less row" do
- tx = {
- booking_date: "2026-01-15",
- transaction_amount: { amount: "100.00", currency: "EUR" },
- credit_debit_indicator: "CRDT"
- }
- base = EnableBankingEntry::Processor.compute_external_id(tx)
- assert base.start_with?("enable_banking_content_")
- assert_equal "#{base}_1", EnableBankingEntry::Processor.compute_external_id(tx, suffix: "1")
- assert_equal "#{base}_abc", EnableBankingEntry::Processor.compute_external_id(tx.dup, suffix: "abc")
- assert_equal base, EnableBankingEntry::Processor.compute_external_id(tx, suffix: nil)
- end
-
- # Pinned on purpose: every id-less row already imported holds this digest for
- # its content. If an unsuffixed row ever hashed differently, every such row
- # would be re-imported as a duplicate.
- test "compute_external_id leaves an unsuffixed row's digest exactly as it was" do
- tx = {
- booking_date: "2026-01-15",
- transaction_amount: { amount: "100.00", currency: "EUR" },
- credit_debit_indicator: "CRDT"
- }
- assert_equal "enable_banking_content_df9c4dcdcc8c891c4f44b1e9a391bcd4", EnableBankingEntry::Processor.compute_external_id(tx)
- end
-
- test "compute_external_id ignores the suffix for a row that carries a provider id" do
- assert_equal "enable_banking_txn_abc", EnableBankingEntry::Processor.compute_external_id({ transaction_id: "txn_abc" }, suffix: "1")
- assert_equal "enable_banking_ref_1", EnableBankingEntry::Processor.compute_external_id({ entry_reference: "ref_1" }, suffix: "1")
- end
-
test "compute_external_id returns nil for transaction with no identifiable content" do
assert_nil EnableBankingEntry::Processor.compute_external_id({})
assert_nil EnableBankingEntry::Processor.compute_external_id(transaction_id: nil, entry_reference: nil)
diff --git a/test/models/enable_banking_item/importer_id_less_test.rb b/test/models/enable_banking_item/importer_id_less_test.rb
index 8574a34cc8..2ca068fccb 100644
--- a/test/models/enable_banking_item/importer_id_less_test.rb
+++ b/test/models/enable_banking_item/importer_id_less_test.rb
@@ -85,127 +85,6 @@ class EnableBankingItem::ImporterIdLessTest < ActiveSupport::TestCase
assert_equal 2, @enable_banking_account.raw_transactions_payload.count
end
- # An ASPSP that sends only date, amount, currency and direction: two
- # same-day transfers of the same amount are, as far as the response can say,
- # two identical rows. Both must reach the payload and the ledger.
- def bare_tx(amount: "100.00", date: Date.current.to_s)
- {
- booking_date: date,
- transaction_amount: { amount: amount, currency: "RON" },
- credit_debit_indicator: "CRDT",
- status: "BOOK"
- }
- end
-
- def stub_fetch(booked)
- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns(booked)
- @importer.stubs(:fetch_paginated_transactions).with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([])
- @importer.stubs(:include_pending?).returns(false)
- @importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)
- end
-
- test "keeps two identical bare rows from one response, end to end" do
- stub_fetch([ bare_tx, bare_tx ])
-
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
- @enable_banking_account.reload
- assert_equal 2, @enable_banking_account.raw_transactions_payload.count, "the in-response dedup must not collapse them"
-
- assert_difference "@account.entries.where(source: \"enable_banking\").count", 2 do
- EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process
- end
- end
-
- test "stores the second of two identical bare rows when it arrives on a later sync" do
- stub_fetch([ bare_tx ])
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
- @enable_banking_account.reload
- assert_equal 1, @enable_banking_account.raw_transactions_payload.count
-
- # The day's second transfer shows up next time, beside the first.
- stub_fetch([ bare_tx, bare_tx ])
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
- @enable_banking_account.reload
- assert_equal 2, @enable_banking_account.raw_transactions_payload.count
-
- # And a third sync of the same response adds nothing.
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
- @enable_banking_account.reload
- assert_equal 2, @enable_banking_account.raw_transactions_payload.count
- end
-
- test "does not store an id-less row again when only a field the hash does not read has changed" do
- stub_fetch([ bare_tx.merge(value_date: Date.current.to_s) ])
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
-
- stub_fetch([ bare_tx.merge(value_date: 1.day.ago.to_date.to_s) ])
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
-
- @enable_banking_account.reload
- assert_equal 1, @enable_banking_account.raw_transactions_payload.count
- end
-
- # A truncated response may leave a stored row out. If it carries a new row
- # with the same content hash in its place, the group has not grown, and
- # counting alone would skip the new row for good.
- test "stores a new row from a truncated response even when the group did not grow" do
- stored = bare_tx.merge(note: "first transfer")
- @enable_banking_account.update!(raw_transactions_payload: [ stored ])
-
- page1 = { transactions: [ bare_tx.merge(note: "second transfer") ], continuation_key: "next" }
- truncation = Provider::EnableBanking::EnableBankingError.new("transactionStatus in request is not the same as in continuationKey", :validation_error)
- @mock_provider.stubs(:get_account_transactions).returns(page1).then.raises(truncation)
- @importer.stubs(:include_pending?).returns(false)
- @importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)
- @enable_banking_item.stubs(:build_psu_headers).returns({})
-
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
-
- @enable_banking_account.reload
- notes = @enable_banking_account.raw_transactions_payload.map { |tx| tx["note"] }
- assert_equal [ "first transfer", "second transfer" ], notes.sort
- end
-
- # Booked and pending rows come from separate fetches. A pending fetch cut
- # short must not loosen the rule for booked rows from a complete fetch.
- test "a truncated pending fetch does not let an edited booked row be stored twice" do
- @enable_banking_account.update!(raw_transactions_payload: [ bare_tx.merge(note: "first transfer") ])
-
- edited = { transactions: [ bare_tx.merge(note: "first transfer, edited") ], continuation_key: nil }
- pending_page = { transactions: [ bare_tx(amount: "7.00") ], continuation_key: "next" }
- truncation = Provider::EnableBanking::EnableBankingError.new("transactionStatus in request is not the same as in continuationKey", :validation_error)
- @mock_provider.stubs(:get_account_transactions).with(has_entry(transaction_status: "BOOK")).returns(edited)
- @mock_provider.stubs(:get_account_transactions).with(has_entry(transaction_status: "PDNG")).returns(pending_page).then.raises(truncation)
- @importer.stubs(:include_pending?).returns(true)
- @importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)
- @enable_banking_item.stubs(:build_psu_headers).returns({})
-
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
-
- @enable_banking_account.reload
- booked = @enable_banking_account.raw_transactions_payload.reject { |tx| tx["_pending"] }
- assert_equal 1, booked.count, "the edited booked row is the stored one, not a second transaction"
- end
-
- test "a complete response still does not store an edited row twice" do
- stored = bare_tx.merge(note: "first transfer")
- @enable_banking_account.update!(raw_transactions_payload: [ stored ])
-
- stub_fetch([ bare_tx.merge(note: "first transfer, edited") ])
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
-
- @enable_banking_account.reload
- assert_equal 1, @enable_banking_account.raw_transactions_payload.count
- end
-
- test "still collapses rows that differ only in entry_reference (issue #954)" do
- stub_fetch([ bare_tx.merge(entry_reference: "ref_a"), bare_tx.merge(entry_reference: "ref_b") ])
- @importer.send(:fetch_and_store_transactions, @enable_banking_account)
-
- @enable_banking_account.reload
- assert_equal 1, @enable_banking_account.raw_transactions_payload.count
- end
-
test "removes stored id-less pending entry when its booked counterpart arrives" do
tx = id_less_tx(amount: "30.00", creditor: "Netflix")
pending_tx = tx.merge(_pending: true)