The personal finance app for everyone (by everyone)
Ruby
fix(enable-banking): replace the fetched window in the stored snapshot (#4159)
Rein Undheimc8df2aa5ef55
diff --git a/app/models/enable_banking_item/importer.rb b/app/models/enable_banking_item/importer.rbindex aa392db527..23adc20543 100644--- a/app/models/enable_banking_item/importer.rb+++ b/app/models/enable_banking_item/importer.rb@@ -938,6 +938,7 @@ class EnableBankingItem::Importertransactions_count = all_transactions.count+ stored_payload = enable_banking_account.raw_transactions_payload.as_json# A copy: pruning the stored array in place would leave the record dirty,# and the guarded write below cannot lock a record with unsaved changes.existing_transactions = enable_banking_account.raw_transactions_payload.to_a.dup@@ -945,10 +946,7 @@ class EnableBankingItem::Importerremoved_pending = falseunless include_pending- removed_pending = existing_transactions.reject! do |tx|- tx = tx.with_indifferent_access- tx.dig(:extra, :enable_banking, :pending) || tx[:_pending] || EnableBankingEntry::Processor.unidentified_hold?(tx)- end+ removed_pending = existing_transactions.reject! { |tx| pending_row?(tx) }endif all_transactions.any?@@ -973,8 +971,7 @@ class EnableBankingItem::Importerif include_pendingremoved_pending ||= existing_transactions.reject! do |tx|tx = tx.with_indifferent_access- pending_flag = tx.dig(:extra, :enable_banking, :pending) || tx[:_pending] || EnableBankingEntry::Processor.unidentified_hold?(tx)- next false unless pending_flag+ next false unless pending_row?(tx)fp = EnableBankingEntry::Processor.compute_external_id(tx)entry_ref = tx[:entry_reference].presence@@ -983,30 +980,40 @@ class EnableBankingItem::Importerendend- # 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+ # Only a fetched row describing the same movement supersedes a stored one.+ # A row the response left out may lie outside the window the ASPSP served,+ # or on a page that was never fetched.+ ids_by_row = external_ids_by_row(existing_transactions + all_transactions)+ superseded_rows = content_pairs(existing_transactions, all_transactions, ids_by_row, ids_by_row).map(&:first)+ superseded_set = Set.new.compare_by_identity.merge(superseded_rows)+ retained_transactions = existing_transactions.reject { |tx| superseded_set.include?(tx) }++ next_snapshot, incoming_transactions = merge_transaction_rows(+ existing_transactions, retained_transactions, all_transactions, ids_by_row+ )- 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)- }.map(&:first)+ if removed_pending || next_snapshot.as_json != existing_transactions.as_json+ # The re-keys and the snapshot they describe commit or roll back together.+ write_snapshot_unless_changed(enable_banking_account, stored_payload) do+ rekey_rotated_identifiers!(+ enable_banking_account, existing_transactions, next_snapshot, superseded_rows, incoming_transactions+ )- if new_transactions.any? || removed_pending- enable_banking_account.upsert_enable_banking_transactions_snapshot!(existing_transactions + new_transactions)+ enable_banking_account.upsert_enable_banking_transactions_snapshot!(next_snapshot)+ endendelsif removed_pending- enable_banking_account.upsert_enable_banking_transactions_snapshot!(- existing_transactions- )+ write_snapshot_unless_changed(enable_banking_account, stored_payload) do+ enable_banking_account.upsert_enable_banking_transactions_snapshot!(existing_transactions)+ endend# A completed first fetch always leaves a payload, even an empty one, so# the next fetch is incremental (nil means "never fetched").if enable_banking_account.raw_transactions_payload.nil?- enable_banking_account.upsert_enable_banking_transactions_snapshot!([])+ write_snapshot_unless_changed(enable_banking_account, stored_payload) do+ enable_banking_account.upsert_enable_banking_transactions_snapshot!([])+ endend{ success: true, transactions_count: transactions_count, truncated: truncated }@@ -1186,22 +1193,133 @@ class EnableBankingItem::Importer[ all_transactions, true ]end+ # Ids are resolved over stored and fetched rows together so rows sharing a+ # transaction_id can still be told apart by entry_reference.+ def external_ids_by_row(rows)+ rows.zip(EnableBankingEntry::Processor.external_ids_for(rows)).to_h+ end++ def merge_transaction_rows(existing_transactions, retained_transactions, fetched_transactions, ids_by_row)+ retained_ids = retained_transactions.map { |row| ids_by_row[row] }.compact.to_set+ incoming_transactions = fetched_transactions.select do |row|+ id = ids_by_row[row]+ id.present? && !retained_ids.include?(id)+ end++ stored_positions = existing_transactions.map { |row| ids_by_row[row] }.each_with_index.to_h+ snapshot = (retained_transactions + incoming_transactions).sort_by.with_index do |row, index|+ [ stored_positions.fetch(ids_by_row[row], existing_transactions.size), index ]+ end+ [ snapshot, incoming_transactions ]+ end+def filter_transactions_by_date(transactions, start_date)return transactions unless start_datetransactions.reject do |tx|- tx = tx.with_indifferent_access- date_str = tx[:booking_date] || tx[:value_date] || tx[:transaction_date]- next false if date_str.blank? # Keep if no date (cannot determine)+ date = row_date(tx)+ date.present? && date < start_date+ end+ end- begin- Date.parse(date_str.to_s) < start_date- rescue ArgumentError- false # Keep if date is unparseable+ # Pairs stored rows with fetched rows describing the same movement. A row that+ # kept its id pairs with itself first, so a reordered response cannot hand one+ # movement's id to another; the rest pair by position, keeping multiplicity.+ def content_pairs(stored_rows, fetched_rows, stored_ids, fetched_ids)+ fetched_by_content = fetched_rows.group_by { |row| content_key(row) }++ stored_rows.group_by { |row| content_key(row) }.flat_map do |key, old_rows|+ new_rows = key && fetched_by_content[key]+ next [] unless new_rows++ unpaired_new = new_rows.dup+ unchanged = []+ rotated = []+ old_rows.each do |old_row|+ old_id = stored_ids[old_row]+ index = old_id.present? && unpaired_new.index { |row| fetched_ids[row] == old_id }+ index ? unchanged << [ old_row, unpaired_new.delete_at(index) ] : rotated << old_row+ end++ unchanged + rotated.zip(unpaired_new).select { |_old_row, new_row| new_row }+ end+ end++ def content_key(transaction)+ content_id = EnableBankingEntry::Processor.compute_external_id(+ transaction.with_indifferent_access.except(:transaction_id, :entry_reference)+ )+ [ pending_row?(transaction), content_id ] if content_id.present?+ end++ # Points existing entries at the ids the ASPSP now uses for the same+ # movements, so the processor updates them (keeping category, merchant,+ # notes and transfer links) instead of inserting beside them.+ def rekey_rotated_identifiers!(enable_banking_account, existing_transactions, next_snapshot, superseded_rows, fetched_rows)+ account = enable_banking_account.current_account+ return if account.blank? || superseded_rows.empty?++ processor = EnableBankingEntry::Processor+ old_ids = existing_transactions.zip(processor.external_ids_for(existing_transactions, account: account)).to_h+ new_ids = next_snapshot.zip(processor.external_ids_for(next_snapshot, account: account)).to_h++ renames = content_pairs(superseded_rows, fetched_rows, old_ids, new_ids).filter_map do |old_row, new_row|+ old_id = old_ids[old_row]+ new_id = new_ids[new_row]+ [ old_id, new_id, new_row ] if old_id.present? && new_id.present? && old_id != new_id+ end+ return if renames.empty?++ entries = account.entries.where(source: "enable_banking")+ taken_ids = entries.where(external_id: renames.map(&:second)).pluck(:external_id).to_set+ entries_by_old_id = entries.where(external_id: renames.map(&:first)).includes(:entryable).lock.index_by(&:external_id)++ renames.each do |old_id, new_id, new_row|+ next if taken_ids.include?(new_id)++ entry = entries_by_old_id[old_id]+ next unless entry && entry.external_id == old_id++ entry.update_column(:external_id, new_id)+ taken_ids << new_id+ if !pending_row?(new_row) && entry.entryable.is_a?(Transaction)+ new_reference = new_row.with_indifferent_access[:entry_reference].to_s.presence+ entry.entryable.update_column(:provider_entry_reference, new_reference)endendend+ # Skips the write when another sync replaced the snapshot after this one read+ # it; re-keying against a stale snapshot would insert a duplicate entry.+ def write_snapshot_unless_changed(enable_banking_account, stored_payload)+ ActiveRecord::Base.transaction do+ enable_banking_account.lock!+ if enable_banking_account.raw_transactions_payload.as_json == stored_payload+ yield+ else+ Rails.logger.info "EnableBankingItem::Importer - snapshot for account #{enable_banking_account.uid} changed during sync, skipping write"+ end+ end+ end++ # Dated as EnableBankingEntry::Processor dates the entry, in the family's zone.+ def row_date(transaction)+ tx = transaction.with_indifferent_access+ return nil if (tx[:booking_date] || tx[:value_date] || tx[:transaction_date]).blank?++ EnableBankingEntry::Processor.transaction_date(tx, enable_banking_item.family&.timezone)+ rescue ArgumentError, TypeError, RangeError+ nil+ end++ # A row is pending either as stored (extra.enable_banking.pending, written by+ # the processor) or as freshly tagged by tag_as_pending during this fetch.+ def pending_row?(transaction)+ tx = transaction.with_indifferent_access+ pending = tx.dig(:extra, :enable_banking, :pending) || tx[:_pending] || EnableBankingEntry::Processor.unidentified_hold?(tx)+ pending ? true : false+ end+def tag_as_pending(transactions)transactions.map { |tx| tx.merge(_pending: true) }enddiff --git a/test/models/enable_banking_item/importer_rotating_ids_test.rb b/test/models/enable_banking_item/importer_rotating_ids_test.rbnew file mode 100644index 0000000000..f9e151bb0d--- /dev/null+++ b/test/models/enable_banking_item/importer_rotating_ids_test.rb@@ -0,0 +1,315 @@+require "test_helper"++# Some ASPSPs re-issue transaction_id and entry_reference on every response, so+# two fetches describe the same movement under different identifiers.+class EnableBankingItem::ImporterRotatingIdsTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @account = accounts(:depository)++ @enable_banking_item = EnableBankingItem.create!(+ family: @family,+ name: "Test EB",+ country_code: "NO",+ application_id: "test_app_id",+ client_certificate: "test_cert",+ session_id: "test_session",+ session_expires_at: 1.day.from_now,+ sync_start_date: 1.month.ago.to_date+ )+ @enable_banking_account = EnableBankingAccount.create!(+ enable_banking_item: @enable_banking_item,+ name: "Current Account",+ uid: "hash_rotating_ids_test",+ account_id: "uuid-rotating-1234",+ currency: "NOK"+ )+ AccountProvider.create!(account: @account, provider: @enable_banking_account)++ @provider = mock()+ @importer = EnableBankingItem::Importer.new(@enable_banking_item, enable_banking_provider: @provider)+ @importer.stubs(:include_pending?).returns(false)+ @importer.stubs(:determine_sync_start_date).returns(1.month.ago.to_date)+ end++ # Same movement, a fresh identifier on each call.+ def rotating_tx(nonce, amount: "100.00", date: Date.current.to_s, counterparty: "Acme")+ {+ transaction_id: "txn_#{nonce}",+ entry_reference: "ref_#{nonce}",+ booking_date: date,+ transaction_amount: { amount: amount, currency: "NOK" },+ credit_debit_indicator: "DBIT",+ creditor: { name: counterparty },+ status: "BOOK"+ }+ end++ def stub_fetch(booked, pending: [], pending_raises: nil, truncated: false)+ @importer.stubs(:fetch_paginated_transactions)+ .with(@enable_banking_account, has_entry(transaction_status: "BOOK")).returns([ booked, truncated ])+ if pending_raises+ @importer.stubs(:fetch_paginated_transactions)+ .with(@enable_banking_account, has_entry(transaction_status: "PDNG")).raises(pending_raises)+ else+ @importer.stubs(:fetch_paginated_transactions)+ .with(@enable_banking_account, has_entry(transaction_status: "PDNG")).returns([ pending, false ])+ end+ end++ def sync(booked, account: @enable_banking_account, **opts)+ stub_fetch(booked, **opts)+ @importer.send(:fetch_and_store_transactions, account)+ @enable_banking_account.reload+ end++ def sync_and_process(booked, **opts)+ sync(booked, **opts)+ process+ end++ def process = EnableBankingAccount::Transactions::Processor.new(@enable_banking_account).process++ def snapshot_count = @enable_banking_account.reload.raw_transactions_payload.count+ def entry_count = Entry.where(account_id: @account.id, source: "enable_banking").count++ test "entries are carried over when the ASPSP rotates identifiers" do+ sync_and_process([ rotating_tx("aaa") ])+ assert_equal 1, entry_count++ sync_and_process([ rotating_tx("bbb") ])+ assert_equal 1, entry_count, "a rotated identifier must not insert a second entry"+ assert_equal 1, snapshot_count++ sync_and_process([ rotating_tx("ccc") ])+ assert_equal 1, entry_count+ end++ test "a re-keyed entry keeps the annotations made on it" do+ sync_and_process([ rotating_tx("aaa") ])+ entry = Entry.find_by(account_id: @account.id, source: "enable_banking")+ category = @family.categories.create!(name: "Groceries #{SecureRandom.hex(4)}")+ entry.entryable.update!(category: category)+ entry.update!(notes: "keep me")++ sync_and_process([ rotating_tx("bbb") ])++ entry.reload+ assert_equal category.id, entry.entryable.category_id+ assert_equal "keep me", entry.notes+ end++ test "genuinely repeated movements keep their multiplicity" do+ three = %w[t1 t2 t3].map { |n| rotating_tx(n, amount: "10.00", counterparty: "Repeat") }+ sync_and_process(three)+ assert_equal 3, snapshot_count+ assert_equal 3, entry_count++ sync_and_process(%w[t4 t5 t6].map { |n| rotating_tx(n, amount: "10.00", counterparty: "Repeat") })+ assert_equal 3, snapshot_count, "must not collapse distinct same-day movements"+ assert_equal 3, entry_count+ end++ test "rotation re-keys both entries that share a transaction id" do+ a = rotating_tx("old_a", amount: "10.00").merge(transaction_id: "old_shared")+ b = rotating_tx("old_b", amount: "20.00").merge(transaction_id: "old_shared")+ sync_and_process([ a, b ])++ entries_by_amount = @account.entries.where(source: "enable_banking").pluck(:amount, :id).to_h+ assert_equal 2, entries_by_amount.size++ new_a = rotating_tx("new_a", amount: "10.00").merge(transaction_id: "new_shared")+ new_b = rotating_tx("new_b", amount: "20.00").merge(transaction_id: "new_shared")+ sync_and_process([ new_b, new_a ])++ assert_equal 2, snapshot_count+ assert_equal 2, entry_count+ assert_equal entries_by_amount, @account.entries.where(source: "enable_banking").pluck(:amount, :id).to_h+ assert_equal "ref_new_a", Entry.find(entries_by_amount.fetch(BigDecimal("10.00"))).transaction.provider_entry_reference+ assert_equal "ref_new_b", Entry.find(entries_by_amount.fetch(BigDecimal("20.00"))).transaction.provider_entry_reference+ end++ test "retains stored rows that predate the fetch" do+ old_row = rotating_tx("old", date: 6.months.ago.to_date.to_s, amount: "999.00")+ @enable_banking_account.upsert_enable_banking_transactions_snapshot!([ old_row ])++ sync([ rotating_tx("new") ])++ stored = @enable_banking_account.raw_transactions_payload.map(&:with_indifferent_access)+ assert_equal 2, stored.count+ assert stored.any? { |t| t[:transaction_amount][:amount].to_s == "999.00" }+ end++ test "an empty response does not wipe the snapshot" do+ sync([ rotating_tx("aaa") ])+ assert_equal 1, snapshot_count++ sync([])+ assert_equal 1, snapshot_count, "a transient empty fetch must not erase history"+ end++ test "an unsupported PDNG fetch still reconciles booked rotations" do+ @importer.stubs(:include_pending?).returns(true)+ sync_and_process([ rotating_tx("aaa") ], pending: [])+ assert_equal 1, snapshot_count+ assert_equal 1, entry_count++ unsupported = Provider::EnableBanking::EnableBankingError.new("PDNG unsupported", :validation_error)+ sync_and_process([ rotating_tx("bbb") ], pending_raises: unsupported)++ stored = @enable_banking_account.raw_transactions_payload.map(&:with_indifferent_access)+ assert_equal 1, stored.count+ assert_equal "txn_bbb", stored.first[:transaction_id]+ assert_equal 1, entry_count, "a rotated identifier must not insert a second entry"+ end++ test "an unsupported PDNG fetch keeps stored pending rows" do+ @importer.stubs(:include_pending?).returns(true)+ pending_row = rotating_tx("pend", amount: "55.00", counterparty: "Pending Co").merge(_pending: true)+ @enable_banking_account.upsert_enable_banking_transactions_snapshot!([ pending_row ])++ unsupported = Provider::EnableBanking::EnableBankingError.new("PDNG unsupported", :validation_error)+ sync([ rotating_tx("bbb") ], pending_raises: unsupported)++ stored = @enable_banking_account.raw_transactions_payload.map(&:with_indifferent_access)+ assert stored.any? { |t| t[:transaction_id] == "txn_pend" },+ "PDNG was never fetched, so stored pending rows cannot be shown to be gone"+ end++ test "a truncated pagination run does not evict rows it never covered" do+ sync([ rotating_tx("aaa", amount: "10.00"), rotating_tx("unfetched", amount: "20.00") ])+ assert_equal 2, snapshot_count++ # The ASPSP repeats its continuation_key, so fetch_paginated_transactions+ # returns the pages it did get and reports the fetch as truncated.+ @importer.unstub(:fetch_paginated_transactions)+ @provider.stubs(:get_account_transactions)+ .returns({ transactions: [ rotating_tx("bbb", amount: "10.00") ], continuation_key: "k1" })+ .then.returns({ transactions: [], continuation_key: "k1" })++ @importer.send(:fetch_and_store_transactions, @enable_banking_account)++ stored = @enable_banking_account.reload.raw_transactions_payload.map { |t| t.with_indifferent_access[:transaction_id] }+ assert_equal %w[txn_bbb txn_unfetched], stored.sort+ end++ test "a truncated fetch from a rotating ASPSP re-keys the rows it did return" do+ sync_and_process([ rotating_tx("aaa", amount: "10.00"), rotating_tx("unfetched", amount: "20.00") ])+ assert_equal 2, entry_count++ sync_and_process([ rotating_tx("bbb", amount: "10.00") ], truncated: true)+ assert_equal 2, entry_count+ assert_equal 2, snapshot_count++ sync_and_process([ rotating_tx("ccc", amount: "10.00"), rotating_tx("unfetched2", amount: "20.00") ])+ assert_equal 2, entry_count+ assert_equal 2, snapshot_count+ end++ test "a complete fetch keeps stored rows it did not return" do+ older = [ 20, 10 ].map { |days| rotating_tx("old#{days}", date: days.days.ago.to_date.to_s, amount: "#{days}.00") }+ @enable_banking_account.upsert_enable_banking_transactions_snapshot!(older)++ sync([ rotating_tx("fresh") ])++ stored = @enable_banking_account.raw_transactions_payload.map { |t| t.with_indifferent_access[:transaction_id] }+ assert_equal %w[txn_fresh txn_old10 txn_old20], stored.sort+ end++ test "a sync that read a snapshot another sync since replaced does not write" do+ sync_and_process([ rotating_tx("aaa") ])+ stale_account = EnableBankingAccount.find(@enable_banking_account.id)++ sync_and_process([ rotating_tx("bbb") ])+ sync([ rotating_tx("ccc") ], account: stale_account)+ process++ assert_equal [ "txn_bbb" ], @enable_banking_account.raw_transactions_payload.map { |t| t.with_indifferent_access[:transaction_id] }+ assert_equal 1, entry_count+ end++ test "an empty first fetch does not overwrite a snapshot another sync stored" do+ stale_account = EnableBankingAccount.find(@enable_banking_account.id)+ assert_nil stale_account.raw_transactions_payload++ sync([ rotating_tx("aaa") ])+ sync([], account: stale_account)++ assert_equal [ "txn_aaa" ], @enable_banking_account.raw_transactions_payload.map { |t| t.with_indifferent_access[:transaction_id] }+ end++ test "an unchanged response does not rewrite the snapshot" do+ sync([ rotating_tx("aaa") ])++ @enable_banking_account.expects(:upsert_enable_banking_transactions_snapshot!).never+ sync([ rotating_tx("aaa") ])+ assert_equal 1, snapshot_count+ end++ test "rotating pending rows are carried over with pending sync on" do+ @importer.stubs(:include_pending?).returns(true)+ pending_tx = ->(nonce) { rotating_tx(nonce, amount: "42.00", counterparty: "Hold Co").merge(status: "PDNG") }++ sync_and_process([ rotating_tx("book_a") ], pending: [ pending_tx.("pend_a") ])+ assert_equal 2, entry_count++ sync_and_process([ rotating_tx("book_b") ], pending: [ pending_tx.("pend_b") ])+ assert_equal 2, entry_count+ assert_equal 2, snapshot_count+ end++ test "row dates are resolved in the family's timezone" do+ @family.update!(timezone: "Pacific/Auckland")+ late_utc = Time.utc(2026, 10, 3, 12, 30)+ rows = [+ { transaction_id: "iso", booking_date: late_utc.iso8601 },+ { transaction_id: "epoch", booking_date: late_utc.to_i }+ ]++ kept = @importer.send(:filter_transactions_by_date, rows, Date.new(2026, 10, 4))++ assert_equal %w[iso epoch], kept.map { |tx| tx[:transaction_id] }+ end++ test "a reordered response does not move annotations between repeated movements" do+ a = rotating_tx("a", amount: "10.00", counterparty: "Repeat")+ b = rotating_tx("b", amount: "10.00", counterparty: "Repeat")+ sync_and_process([ a, b ])+ assert_equal 2, entry_count++ b_id = EnableBankingEntry::Processor.compute_external_id(b.with_indifferent_access)+ b_entry = Entry.find_by!(account_id: @account.id, source: "enable_banking", external_id: b_id)+ b_entry.update!(notes: "belongs to b")++ # b keeps its identifier, a rotates to c, and the order flips.+ c = rotating_tx("c", amount: "10.00", counterparty: "Repeat")+ sync_and_process([ b, c ])++ assert_equal 2, entry_count, "pairing must not orphan an entry and insert a replacement"+ assert_equal "belongs to b", Entry.find_by(account_id: @account.id, source: "enable_banking", external_id: b_id)&.notes,+ "an unchanged identifier must keep its own annotations"+ end++ test "a numeric timestamp is read as a timestamp, not as a four-digit year" do+ start_date = Date.new(2026, 9, 12)+ # 1791072000 is 2026-10-04; read as digits, Date.parse takes it for the year 1791.+ in_window = { transaction_id: "epoch_in", booking_date: 1791072000 }+ out_of_window = { transaction_id: "epoch_out", booking_date: Date.new(2026, 1, 5).to_time.to_i }++ kept = @importer.send(:filter_transactions_by_date, [ in_window, out_of_window ], start_date)++ assert_equal [ "epoch_in" ], kept.map { |tx| tx[:transaction_id] }+ end++ test "a failed snapshot write rolls back the re-keyed identifiers" do+ sync_and_process([ rotating_tx("aaa") ])+ entry = Entry.find_by!(account_id: @account.id, source: "enable_banking")+ old_external_id = entry.external_id++ @enable_banking_account.stubs(:upsert_enable_banking_transactions_snapshot!).raises(ActiveRecord::StatementInvalid, "boom")+ sync([ rotating_tx("bbb") ])++ assert_equal old_external_id, entry.reload.external_id,+ "re-keying must not outlive the snapshot write it was paired with"+ end+end