Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Keep Redbark entries when the bank re-issues ids (#4379)

jaysbeekay6237bd7e8dbe
diff --git a/app/models/redbark_account/transaction_id_reissue.rb b/app/models/redbark_account/transaction_id_reissue.rb
new file mode 100644
index 0000000000..1fed885534
--- /dev/null
+++ b/app/models/redbark_account/transaction_id_reissue.rb
@@ -0,0 +1,122 @@
+# frozen_string_literal: true
+
+# Finds the transactions a bank re-issued under a new id between two syncs.
+#
+# Redbark passes bank ids through unchanged, and some banks re-issue them: the
+# description is shortened and a new id appears while the old one stops being
+# served, or the bank sends no ids for a while and Fiskil generates
+# `bank_tx_s_` ones. Entries are keyed by id, so without this each re-issue
+# imports a second entry.
+#
+# Within one sync, a stored posted row that vanished from the fetch window is
+# paired with a newly seen row only when the two agree on amount, sit at most
+# MAX_DATE_GAP days apart, are related (equal real references, or else equal
+# descriptions, or one at least MIN_PREFIX_LENGTH long that prefixes the
+# other) and each is the other's only candidate.
+# Anything ambiguous is left alone, so the worst case is today's duplicate.
+class RedbarkAccount::TransactionIdReissue
+ include RedbarkAccount::DataHelpers
+
+ GENERATED_ID_PREFIX = "bank_tx_s_"
+ MAX_DATE_GAP = 3
+ # A shorter description prefixes too many unrelated ones ("FEE" of "FEE
+ # REVERSAL"). The truncations seen keep the transfer number and most of
+ # the account, well past this.
+ MIN_PREFIX_LENGTH = 16
+ # "0" is a placeholder on provisional rows, never a real reference
+ PLACEHOLDER_REFERENCES = [ "0" ].freeze
+
+ # re_keys: [old_id, new_id] pairs where the entry should follow the new id.
+ # aliases: [kept_id, generated_id] pairs where the entry keeps its id.
+ Result = Data.define(:re_keys, :aliases)
+
+ def initialize(stored:, fetched:, window_start:, known_alias_ids: [])
+ @stored = stored.map { |t| normalize(t) }
+ @fetched = fetched.map { |t| normalize(t) }
+ @window_start = window_start
+ @known_alias_ids = known_alias_ids.map(&:to_s).to_set
+ end
+
+ def call
+ re_keys = []
+ aliases = []
+
+ pairs.each do |vanished, replacement|
+ if replacement[:id].start_with?(GENERATED_ID_PREFIX)
+ aliases << [ vanished[:id], replacement[:id] ]
+ else
+ re_keys << [ vanished[:id], replacement[:id] ]
+ end
+ end
+
+ Result.new(re_keys: re_keys, aliases: aliases)
+ end
+
+ private
+
+ def pairs
+ return [] if @window_start.nil?
+
+ candidates = vanished_rows.index_with do |vanished|
+ new_rows.select { |row| same_transaction?(vanished, row) }
+ end
+
+ candidates.filter_map do |vanished, matches|
+ next unless matches.one?
+
+ replacement = matches.first
+ next unless candidates.count { |_, other| other.include?(replacement) } == 1
+
+ [ vanished, replacement ]
+ end
+ end
+
+ def vanished_rows
+ fetched_ids = @fetched.map { |t| t[:id] }.to_set
+
+ @stored.select do |t|
+ posted?(t) && t[:date].present? && t[:date] >= @window_start && !fetched_ids.include?(t[:id])
+ end
+ end
+
+ def new_rows
+ stored_ids = @stored.map { |t| t[:id] }.to_set
+
+ @fetched.select do |t|
+ posted?(t) && t[:date].present? && !stored_ids.include?(t[:id]) && !@known_alias_ids.include?(t[:id])
+ end
+ end
+
+ def same_transaction?(vanished, row)
+ vanished[:amount].present? && vanished[:amount] == row[:amount] &&
+ (vanished[:date] - row[:date]).abs <= MAX_DATE_GAP &&
+ related?(vanished, row)
+ end
+
+ def related?(a, b)
+ if a[:reference] && b[:reference]
+ a[:reference] == b[:reference]
+ else
+ x, y = [ a[:description], b[:description] ].sort_by(&:length)
+ x.present? && (x == y || (x.length >= MIN_PREFIX_LENGTH && y.start_with?(x)))
+ end
+ end
+
+ def posted?(t)
+ t[:id].present? && t[:status] != "pending"
+ end
+
+ def normalize(transaction)
+ t = transaction.with_indifferent_access
+ reference = t[:reference].to_s.strip
+
+ {
+ id: t[:id].to_s,
+ status: t[:status].to_s,
+ date: parse_date(t[:date] || t[:postDate]),
+ amount: parse_decimal(t[:amount]),
+ description: t[:description].to_s.squish.downcase,
+ reference: reference.blank? || PLACEHOLDER_REFERENCES.include?(reference) ? nil : reference
+ }
+ end
+end
diff --git a/app/models/redbark_account/transactions/processor.rb b/app/models/redbark_account/transactions/processor.rb
index 6d2ad8e61b..13346584f4 100644
--- a/app/models/redbark_account/transactions/processor.rb
+++ b/app/models/redbark_account/transactions/processor.rb
@@ -118,7 +118,7 @@ class RedbarkAccount::Transactions::Processor
# Transactions carry no per-item currency; they are in the account's currency
currency = account.currency
- extra = build_extra_metadata(data)
+ extra = build_extra_metadata(data, external_id)
Rails.logger.debug "RedbarkAccount::Transactions::Processor - Importing transaction: id=#{external_id} date=#{date}"
@@ -132,7 +132,8 @@ class RedbarkAccount::Transactions::Processor
source: "redbark",
merchant: merchant_for(data),
notes: data[:description].presence,
- extra: extra
+ extra: extra,
+ replace_extra_namespaces: [ "redbark" ]
)
end
@@ -162,7 +163,11 @@ class RedbarkAccount::Transactions::Processor
nil
end
- def build_extra_metadata(data)
+ # The "redbark" namespace is replaced on every import, so a field Redbark
+ # stops sending is cleared rather than kept by a deep merge. alias_ids is
+ # Sure's own record (RedbarkItem::Importer#record_alias), so it is carried
+ # over from the stored entry.
+ def build_extra_metadata(data, external_id)
{
"redbark" => {
"id" => data[:id],
@@ -170,8 +175,20 @@ class RedbarkAccount::Transactions::Processor
"merchant" => data[:merchantName],
"category" => data[:category],
"merchant_category_code" => data[:merchantCategoryCode],
- "direction" => data[:direction]
+ "direction" => data[:direction],
+ "reference" => data[:reference].presence,
+ "extended_description" => data[:extendedDescription].presence,
+ "alias_ids" => alias_ids_by_external_id[external_id]
}.compact
}
end
+
+ def alias_ids_by_external_id
+ @alias_ids_by_external_id ||= account.entries
+ .where(source: "redbark", entryable_type: "Transaction")
+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
+ .where("transactions.extra -> 'redbark' -> 'alias_ids' IS NOT NULL")
+ .pluck(:external_id, Arel.sql("transactions.extra -> 'redbark' -> 'alias_ids'"))
+ .to_h
+ end
end
diff --git a/app/models/redbark_item/importer.rb b/app/models/redbark_item/importer.rb
index e72f909ff4..47ca88e0d8 100644
--- a/app/models/redbark_item/importer.rb
+++ b/app/models/redbark_item/importer.rb
@@ -152,12 +152,18 @@ class RedbarkItem::Importer
if transactions_data.any?
transactions_hashes = transactions_data.map { |t| sdk_object_to_hash(t) }
- merged = merge_transactions(
- redbark_account.raw_transactions_payload || [],
- transactions_hashes,
- window_start: start_date
- )
- redbark_account.upsert_redbark_transactions_snapshot!(merged)
+ stored = redbark_account.raw_transactions_payload || []
+
+ RedbarkAccount.transaction do
+ dropped_stored_ids, kept_ids_by_alias = apply_reissued_ids(redbark_account, stored, transactions_hashes, start_date)
+
+ merged = merge_transactions(
+ stored.reject { |t| dropped_stored_ids.include?(transaction_key(t)) },
+ fold_aliases(transactions_hashes, kept_ids_by_alias, dropped_stored_ids),
+ window_start: start_date
+ )
+ redbark_account.upsert_redbark_transactions_snapshot!(merged)
+ end
stats["transactions_found"] = stats.fetch("transactions_found", 0) + transactions_data.size
end
rescue Provider::Redbark::AuthenticationError
@@ -357,6 +363,96 @@ class RedbarkItem::Importer
by_id.values
end
+ # Points existing entries at the ids a bank re-issued (see
+ # RedbarkAccount::TransactionIdReissue). Returns the stored ids to leave
+ # out of the snapshot, so the processor can't import the old row as a
+ # second entry, and { generated id => kept id } for fold_aliases.
+ #
+ # A re-key moves only external_id: a protected entry keeps everything
+ # else, and an unprotected one is refreshed from the new row by the
+ # processor as usual. A generated id is recorded as an alias on the entry
+ # it duplicates, which keeps its id for when the bank restores it; with no
+ # such entry it is handled like any other new id.
+ def apply_reissued_ids(redbark_account, stored, fetched, window_start)
+ entries = redbark_account.current_account&.entries&.where(source: "redbark")
+ return [ Set.new, {} ] if entries.nil?
+
+ kept_ids_by_alias = entries.where(entryable_type: "Transaction")
+ .joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
+ .where("transactions.extra -> 'redbark' -> 'alias_ids' IS NOT NULL")
+ .pluck(:external_id, Arel.sql("transactions.extra -> 'redbark' -> 'alias_ids'"))
+ .each_with_object({}) do |(external_id, alias_ids), map|
+ Array(alias_ids).each { |alias_id| map[alias_id.to_s] = external_id.delete_prefix("redbark_") }
+ end
+
+ result = RedbarkAccount::TransactionIdReissue.new(
+ stored: stored, fetched: fetched, window_start: window_start, known_alias_ids: kept_ids_by_alias.keys
+ ).call
+
+ dropped_stored_ids = Set.new
+
+ result.aliases.each do |kept_id, generated_id|
+ entry = entries.find_by(external_id: "redbark_#{kept_id}", entryable_type: "Transaction")
+
+ if entry
+ record_alias(entry.entryable, generated_id)
+ kept_ids_by_alias[generated_id] = kept_id
+ else
+ dropped_stored_ids << kept_id
+ end
+ end
+
+ result.re_keys.each do |old_id, new_id|
+ dropped_stored_ids << old_id
+
+ if entries.exists?(external_id: "redbark_#{new_id}")
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: "Redbark re-issued a transaction id that already has an entry; left both entries as they are",
+ source: self.class.name,
+ provider_key: "redbark",
+ family: redbark_item.family,
+ account_provider: redbark_account.account_provider,
+ metadata: { redbark_account_id: redbark_account.id, old_id: old_id, new_id: new_id }
+ )
+ next
+ end
+
+ entries.where(external_id: "redbark_#{old_id}")
+ .update_all(external_id: "redbark_#{new_id}", updated_at: Time.current)
+ end
+
+ [ dropped_stored_ids, kept_ids_by_alias ]
+ end
+
+ # A generated id stands in for its kept id. While it is the only row of
+ # the two served, its payload is the current one, so it goes into the
+ # snapshot under the kept id and the processor refreshes the kept entry
+ # from it. It is dropped once the kept id is served again, or when the
+ # kept row left the snapshot this sync (re-keyed away).
+ def fold_aliases(fetched, kept_ids_by_alias, dropped_stored_ids)
+ fetched_ids = fetched.map { |t| transaction_key(t) }.to_set
+
+ fetched.filter_map do |t|
+ kept_id = kept_ids_by_alias[transaction_key(t)]
+ next t unless kept_id
+ next if fetched_ids.include?(kept_id) || dropped_stored_ids.include?(kept_id)
+
+ t.merge(t.key?(:id) ? { id: kept_id } : { "id" => kept_id })
+ end
+ end
+
+ def record_alias(transaction, generated_id)
+ extra = (transaction.extra || {}).deep_dup
+ redbark = extra["redbark"] || {}
+ alias_ids = Array(redbark["alias_ids"])
+ return if alias_ids.include?(generated_id)
+
+ extra["redbark"] = redbark.merge("alias_ids" => alias_ids + [ generated_id ])
+ transaction.update_columns(extra: extra)
+ end
+
def within_window?(transaction, window_start)
return true if window_start.nil?
diff --git a/test/models/redbark_account/transaction_id_reissue_test.rb b/test/models/redbark_account/transaction_id_reissue_test.rb
new file mode 100644
index 0000000000..1af3232d2b
--- /dev/null
+++ b/test/models/redbark_account/transaction_id_reissue_test.rb
@@ -0,0 +1,165 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+class RedbarkAccount::TransactionIdReissueTest < ActiveSupport::TestCase
+ setup do
+ @window_start = Date.new(2026, 9, 1)
+ end
+
+ test "pairs a shortened description with the row it replaced" do
+ stored = [ row("A", "TRANSFER 1000000001 FROM 000-111-222333", reference: "0") ]
+ fetched = [ row("B", "TRANSFER 1000000001 FROM 000-111-222", reference: "75400000000000000000001") ]
+
+ result = detect(stored, fetched)
+
+ assert_equal [ %w[A B] ], result.re_keys
+ assert_empty result.aliases
+ end
+
+ test "pairs rows with equal real references whatever their descriptions" do
+ stored = [ row("A", "CARD PURCHASE 4411", reference: "0522100624") ]
+ fetched = [ row("B", "Coffee Shop Sydney", reference: "0522100624") ]
+
+ assert_equal [ %w[A B] ], detect(stored, fetched).re_keys
+ end
+
+ test "pairs dates three days apart and no further" do
+ stored = [ row("A", "TRANSFER 1000000001", date: "2026-09-10") ]
+
+ assert_equal [ %w[A B] ], detect(stored, [ row("B", "TRANSFER 1000000001", date: "2026-09-13") ]).re_keys
+ assert_empty detect(stored, [ row("B", "TRANSFER 1000000001", date: "2026-09-14") ]).re_keys
+ end
+
+ test "aliases a generated id instead of re-keying" do
+ stored = [ row("A", "FALLS RESTAURANT 94.06") ]
+ fetched = [ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ]
+
+ result = detect(stored, fetched)
+
+ assert_equal [ %w[A bank_tx_s_X] ], result.aliases
+ assert_empty result.re_keys
+ end
+
+ test "leaves genuine look-alikes alone while both are still served" do
+ stored = [ row("A", "FALLS RESTAURANT", reference: "476053") ]
+ fetched = [ row("A", "FALLS RESTAURANT", reference: "476053"), row("C", "FALLS RESTAURANT", reference: "199002") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "leaves a stored row alone while it is still served beside an identical new one" do
+ stored = [ row("A", "BUS FARE 9.03") ]
+ fetched = [ row("A", "BUS FARE 9.03"), row("C", "BUS FARE 9.03") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ # A short description is a prefix of too many others: "FEE" of
+ # "FEE REVERSAL", "UBER" of "UBER EATS".
+ test "leaves a short description that prefixes a longer one alone" do
+ assert_no_pairs detect([ row("A", "FEE") ], [ row("B", "FEE REVERSAL") ])
+ assert_no_pairs detect([ row("A", "UBER EATS SYDNEY") ], [ row("B", "UBER") ])
+ end
+
+ test "pairs a prefix at the minimum length and not one character shorter" do
+ shorter = "a" * RedbarkAccount::TransactionIdReissue::MIN_PREFIX_LENGTH
+
+ assert_equal [ %w[A B] ], detect([ row("A", "#{shorter} more") ], [ row("B", shorter) ]).re_keys
+ assert_no_pairs detect([ row("A", "#{shorter} more") ], [ row("B", shorter.chop) ])
+ end
+
+ test "pairs equal short descriptions" do
+ assert_equal [ %w[A B] ], detect([ row("A", "FEE") ], [ row("B", "FEE") ]).re_keys
+ end
+
+ test "leaves a vanished row with no new candidate alone" do
+ assert_no_pairs detect([ row("A", "TRANSFER 1") ], [ row("Z", "SOMETHING ELSE", amount: "-1.00") ])
+ end
+
+ test "leaves a vanished row with two related new rows alone" do
+ stored = [ row("A", "TRANSFER 1000000001 FROM 000-111-222333") ]
+ fetched = [ row("B", "TRANSFER 1000000001 FROM 000-111-222"), row("C", "TRANSFER 1000000001 FROM 000-111") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "leaves twin vanished rows that match one new row alone" do
+ stored = [ row("F1", "ACCOUNT FEE", reference: "9001"), row("F2", "ACCOUNT FEE", reference: "9001") ]
+ fetched = [ row("G1", "ACCOUNT FEE", reference: "9001") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "leaves a different amount alone" do
+ assert_no_pairs detect([ row("A", "TRANSFER 1") ], [ row("B", "TRANSFER 1", amount: "-50.01") ])
+ end
+
+ test "leaves unrelated descriptions without a real reference alone" do
+ assert_no_pairs detect([ row("A", "TRANSFER 1000000001") ], [ row("B", "PAYMENT RECEIVED THANK YOU") ])
+ end
+
+ test "never pairs on a shared reference across different amounts" do
+ stored = [ row("A", "BVH 505.90", amount: "-505.90", reference: "0522100623") ]
+ fetched = [ row("B", "BVH 486.12", amount: "-486.12", reference: "0522100623") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "treats a zero reference as absent" do
+ stored = [ row("A", "ACCOUNT FEE", reference: "0") ]
+ fetched = [ row("B", "INTEREST CHARGED", reference: "0") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "falls back to descriptions when only one row has a real reference" do
+ stored = [ row("A", "TRANSFER 1000000001", reference: "0522100624") ]
+ fetched = [ row("B", "PAYMENT RECEIVED", reference: "") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "ignores pending rows on both sides" do
+ stored = [ row("A", "TRANSFER 1", status: "pending") ]
+ fetched = [ row("B", "TRANSFER 1") ]
+ assert_no_pairs detect(stored, fetched)
+
+ stored = [ row("A", "TRANSFER 1") ]
+ fetched = [ row("B", "TRANSFER 1", status: "pending") ]
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "ignores stored rows dated before the fetch window" do
+ stored = [ row("A", "TRANSFER 1", date: "2026-08-31") ]
+ fetched = [ row("B", "TRANSFER 1", date: "2026-09-01") ]
+
+ assert_no_pairs detect(stored, fetched)
+ end
+
+ test "does not pair a fetched id already recorded as an alias" do
+ stored = [ row("A", "FALLS RESTAURANT 94.06") ]
+ fetched = [ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ]
+
+ result = RedbarkAccount::TransactionIdReissue.new(
+ stored: stored, fetched: fetched, window_start: @window_start, known_alias_ids: [ "bank_tx_s_X" ]
+ ).call
+
+ assert_no_pairs result
+ end
+
+ private
+
+ def detect(stored, fetched)
+ RedbarkAccount::TransactionIdReissue.new(stored: stored, fetched: fetched, window_start: @window_start).call
+ end
+
+ def row(id, description, amount: "-50.00", date: "2026-09-10", reference: nil, status: "posted")
+ { "id" => id, "status" => status, "date" => date, "amount" => amount, "description" => description, "reference" => reference }.compact
+ end
+
+ def assert_no_pairs(result)
+ assert_empty result.re_keys
+ assert_empty result.aliases
+ end
+end
diff --git a/test/models/redbark_item/importer_reissued_ids_test.rb b/test/models/redbark_item/importer_reissued_ids_test.rb
new file mode 100644
index 0000000000..ec7d3591fd
--- /dev/null
+++ b/test/models/redbark_item/importer_reissued_ids_test.rb
@@ -0,0 +1,268 @@
+# frozen_string_literal: true
+
+require "test_helper"
+
+# A bank can re-issue a transaction under a new id: the description is
+# shortened and a new id appears while the old one stops being served, or the
+# bank sends no ids for a while and Fiskil generates `bank_tx_s_` ones. Each
+# test syncs through the importer and then the processor, the way a real sync
+# does, so a row left in the snapshot shows up as an entry.
+class RedbarkItem::ImporterReissuedIdsTest < ActiveSupport::TestCase
+ ORIGINAL = "TRANSFER 1000000001 FROM 000-111-222333"
+ SHORTENED = "TRANSFER 1000000001 FROM 000-111-222"
+
+ setup do
+ @redbark_item = redbark_items(:one)
+ @redbark_account = redbark_accounts(:savings_account)
+ @family = @redbark_item.family
+ @account = @family.accounts.create!(name: "Card", balance: 0, currency: "AUD", accountable: CreditCard.new)
+ @redbark_account.ensure_account_provider!(@account)
+ @redbark_account.reload
+
+ @date = (Date.current - 2).to_s
+ # Incremental window: last_synced_at - 7 days
+ @redbark_item.stubs(:last_synced_at).returns(Time.current)
+ end
+
+ test "a shortened description moves the existing entry to the new id" do
+ entry = import_original(row("A", ORIGINAL, reference: "0"))
+ category = categories(:income)
+ entry.transaction.update!(category: category)
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("B", SHORTENED, reference: "75400000000000000000001") ])
+ end
+
+ entry.reload
+ assert_equal "redbark_B", entry.external_id
+ assert_equal category, entry.transaction.category
+ assert_equal SHORTENED, entry.notes
+ assert_equal [ "B" ], snapshot_ids
+ end
+
+ test "a second sync after the move re-creates nothing" do
+ import_original(row("A", ORIGINAL, reference: "0"))
+ fetched = [ row("B", SHORTENED, reference: "75400000000000000000001") ]
+ sync(fetched)
+
+ assert_no_difference -> { @account.entries.count } do
+ sync(fetched)
+ end
+ assert_nil @account.entries.find_by(external_id: "redbark_A")
+ end
+
+ test "equal real references move the entry whatever the descriptions" do
+ entry = import_original(row("A", "CARD PURCHASE 4411", reference: "0522100624"))
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("B", "Coffee Shop Sydney", reference: "0522100624") ])
+ end
+ assert_equal "redbark_B", entry.reload.external_id
+ end
+
+ test "a generated id becomes an alias and the restored id still matches" do
+ entry = import_original(row("A", "FALLS RESTAURANT 94.06"))
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ])
+ end
+ entry.reload
+ assert_equal "redbark_A", entry.external_id
+ assert_equal [ "bank_tx_s_X" ], entry.transaction.extra.dig("redbark", "alias_ids")
+ assert_not_includes snapshot_ids, "bank_tx_s_X"
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ])
+ sync([ row("A", "FALLS RESTAURANT 94.06") ])
+ end
+ assert_equal "redbark_A", entry.reload.external_id
+ end
+
+ test "an aliased id served beside the restored one adds nothing" do
+ import_original(row("A", "FALLS RESTAURANT 94.06"))
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ])
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("A", "FALLS RESTAURANT 94.06"), row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ])
+ end
+ assert_not_includes snapshot_ids, "bank_tx_s_X"
+ end
+
+ # While the generated id is the only row served, its payload is the
+ # current one, so it reaches the kept entry under the kept id.
+ test "a generated id's payload reaches the kept entry while it is the only row served" do
+ entry = import_original(row("A", "FALLS RESTAURANT 94.06"))
+
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06 ZA") ])
+ assert_equal "FALLS RESTAURANT 94.06 ZA", entry.reload.notes
+ assert_equal [ "A" ], snapshot_ids
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06 ZAR", amount: "51.00") ])
+ end
+ entry.reload
+ assert_equal "redbark_A", entry.external_id
+ assert_equal "FALLS RESTAURANT 94.06 ZAR", entry.notes
+ assert_equal(-51, entry.amount.to_i)
+ assert_equal [ "A" ], snapshot_ids
+ end
+
+ test "the restored id's payload wins over an aliased id served beside it" do
+ entry = import_original(row("A", "FALLS RESTAURANT 94.06"))
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ])
+
+ sync([ row("A", "FALLS RESTAURANT RESTORED"), row("bank_tx_s_X", "FALLS RESTAURANT 94.06 ZA") ])
+
+ assert_equal "FALLS RESTAURANT RESTORED", entry.reload.notes
+ assert_equal [ "A" ], snapshot_ids
+ end
+
+ test "an aliased id is dropped once its kept entry is re-keyed" do
+ entry = import_original(row("A", "TRANSFER 1000000001 FROM 000-111-222333"))
+ sync([ row("bank_tx_s_X", "TRANSFER 1000000001 FROM 000-111-222333") ])
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("bank_tx_s_X", "TRANSFER 1000000001 FROM 000-111-222333"), row("B", "TRANSFER 1000000001 FROM 000-111-222") ])
+ sync([ row("bank_tx_s_X", "TRANSFER 1000000001 FROM 000-111-222333"), row("B", "TRANSFER 1000000001 FROM 000-111-222") ])
+ end
+ assert_equal "redbark_B", entry.reload.external_id
+ assert_equal [ "B" ], snapshot_ids
+ end
+
+ test "the alias survives the processor's next import of the entry" do
+ entry = import_original(row("A", "FALLS RESTAURANT 94.06"))
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ])
+ sync([ row("A", "FALLS RESTAURANT 94.06") ])
+
+ assert_equal [ "bank_tx_s_X" ], entry.reload.transaction.extra.dig("redbark", "alias_ids")
+ end
+
+ test "a reference Redbark stops sending is cleared from the transaction" do
+ entry = import_original(row("A", ORIGINAL, reference: "75400000000000000000001"))
+ assert_equal "75400000000000000000001", entry.transaction.extra.dig("redbark", "reference"), "precondition"
+
+ sync([ row("A", ORIGINAL) ])
+
+ assert_not entry.reload.transaction.extra["redbark"].key?("reference")
+ end
+
+ test "a reference Redbark stops sending is cleared from a user-modified transaction" do
+ entry = import_original(row("A", ORIGINAL, reference: "75400000000000000000001"))
+ entry.update!(name: "Card repayment", user_modified: true)
+
+ sync([ row("A", ORIGINAL) ])
+
+ entry.reload
+ assert_equal "Card repayment", entry.name
+ assert_not entry.transaction.extra["redbark"].key?("reference")
+ end
+
+ test "a generated id with no entry to alias is imported" do
+ @redbark_account.update!(raw_transactions_payload: [ row("A", "FALLS RESTAURANT 94.06") ])
+
+ assert_difference -> { @account.entries.count }, 1 do
+ sync([ row("bank_tx_s_X", "FALLS RESTAURANT 94.06") ])
+ end
+ assert @account.entries.exists?(external_id: "redbark_bank_tx_s_X")
+ end
+
+ test "genuine look-alikes both still served stay two entries" do
+ import_original(row("A", "FALLS RESTAURANT", reference: "476053"))
+
+ assert_difference -> { @account.entries.count }, 1 do
+ sync([ row("A", "FALLS RESTAURANT", reference: "476053"), row("C", "FALLS RESTAURANT", reference: "199002") ])
+ end
+ assert @account.entries.exists?(external_id: "redbark_A")
+ assert @account.entries.exists?(external_id: "redbark_C")
+ end
+
+ test "an excluded entry moves to the new id and keeps its name and exclusion" do
+ entry = import_original(row("A", ORIGINAL, reference: "0"))
+ entry.update!(excluded: true)
+ name_before = entry.name
+ notes_before = entry.notes
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("B", SHORTENED, reference: "75400000000000000000001") ])
+ end
+
+ entry.reload
+ assert_equal "redbark_B", entry.external_id
+ assert entry.excluded?
+ assert_equal name_before, entry.name
+ assert_equal notes_before, entry.notes
+ end
+
+ test "a user-modified entry moves to the new id and keeps its name" do
+ entry = import_original(row("A", ORIGINAL, reference: "0"))
+ entry.update!(name: "Card repayment", user_modified: true)
+
+ sync([ row("B", SHORTENED, reference: "75400000000000000000001") ])
+
+ entry.reload
+ assert_equal "redbark_B", entry.external_id
+ assert_equal "Card repayment", entry.name
+ end
+
+ test "an existing entry for the new id blocks the move" do
+ original = import_original(row("A", ORIGINAL, reference: "0"))
+ copy = @account.entries.create!(
+ name: "Copy", date: @date, amount: -50, currency: "AUD", external_id: "redbark_B", source: "redbark",
+ entryable: Transaction.new
+ )
+
+ assert_no_difference -> { @account.entries.count } do
+ assert_difference -> { DebugLogEntry.where(provider_key: "redbark").count }, 1 do
+ sync([ row("B", SHORTENED, reference: "75400000000000000000001") ])
+ end
+ end
+ assert_equal "redbark_A", original.reload.external_id
+ assert_equal "redbark_B", copy.reload.external_id
+ assert_equal [ "B" ], snapshot_ids
+ end
+
+ test "a changed description on the same id pairs nothing" do
+ entry = import_original(row("A", "GP75122326249061325002498 399.97ZA"))
+
+ assert_no_difference -> { @account.entries.count } do
+ sync([ row("A", "GP399.97 ZAR", reference: "75122326249061325002498") ])
+ end
+ entry.reload
+ assert_equal "redbark_A", entry.external_id
+ assert_equal "GP399.97 ZAR", entry.notes
+ end
+
+ test "the reference is stored on the transaction" do
+ import_original(row("A", ORIGINAL, reference: "0"))
+ sync([ row("A", ORIGINAL, reference: "75400000000000000000001") ])
+
+ extra = @account.entries.find_by(external_id: "redbark_A").transaction.extra["redbark"]
+ assert_equal "75400000000000000000001", extra["reference"]
+ end
+
+ private
+
+ def row(id, description, reference: nil, amount: "50.00", status: "posted")
+ { "id" => id, "status" => status, "date" => @date, "amount" => amount, "description" => description, "reference" => reference }.compact
+ end
+
+ def import_original(original)
+ @redbark_account.update!(raw_transactions_payload: [ original ])
+ RedbarkAccount::Transactions::Processor.new(@redbark_account).process
+ @account.entries.find_by!(external_id: "redbark_#{original["id"]}")
+ end
+
+ def sync(fetched)
+ provider = mock("redbark_provider")
+ provider.stubs(:list_connections).returns([])
+ provider.stubs(:get_transactions).returns(fetched)
+
+ RedbarkItem::Importer.new(@redbark_item, redbark_provider: provider).send(:import_transactions, @redbark_account)
+ @redbark_account.reload
+ RedbarkAccount::Transactions::Processor.new(@redbark_account).process
+ end
+
+ def snapshot_ids
+ @redbark_account.reload.raw_transactions_payload.map { |t| t["id"] }
+ end
+end