Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Stop claiming ambiguous pending matches on import (#4215)

GFRa748b7927586
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rb
index ccb4479d0a..395a6bc289 100644
--- a/app/models/account/provider_import_adapter.rb
+++ b/app/models/account/provider_import_adapter.rb
@@ -58,6 +58,16 @@ class Account::ProviderImportAdapter
# the protection check (pending→booked bypass) and the auto-claim path below.
incoming_pending = extra.is_a?(Hash) && Transaction.pending_extra?(extra.with_indifferent_access)
+ # An automatically excluded stale pending (see Entry.auto_exclude_stale_pending)
+ # that the provider now delivers as booked under the same id becomes a normal
+ # entry again. Entries the user excluded are never touched. An import_locked
+ # entry that is not user_modified keeps its pending flag below, so it stays
+ # excluded rather than being re-excluded on every sync.
+ if entry.persisted? && !incoming_pending && entry.auto_excluded_pending? &&
+ (entry.user_modified? || !entry.import_locked?)
+ entry.update!(excluded: false) # also drops the mark (Entry callback)
+ end
+
# === PROTECTION CHECK: Skip entries that should not be overwritten ===
# Check persisted Transaction entries for protection flags before making changes.
# This prevents sync from overwriting user edits, CSV imports, or excluded entries.
@@ -876,7 +886,7 @@ class Account::ProviderImportAdapter
# @param currency [String] Currency code
# @param source [String] Provider name (e.g., "simplefin")
# @param date_window [Integer] Days to search around the posted date (default: 8)
- # @return [Entry, nil] The pending entry or nil if not found
+ # @return [Entry, nil] The pending entry, or nil when none or several match
def find_pending_transaction(date:, amount:, currency:, source:, date_window: 8)
date = Date.parse(date.to_s) unless date.is_a?(Date)
@@ -896,9 +906,15 @@ class Account::ProviderImportAdapter
.where(currency: currency)
.where(date: (date - date_window.days)..date) # Pending must be ON or BEFORE posted date
.where(Transaction.pending_sql("transactions"))
- .order(date: :desc) # Prefer most recent pending transaction
+ .where(excluded: false)
+ .limit(2)
+ .to_a
- candidates.first
+ # Amount, currency and date alone cannot tell two same-amount pendings apart,
+ # so only claim when the match is unambiguous (#2013). Otherwise the posted
+ # transaction is imported as a new entry and the pendings stay for the
+ # stale-pending cleanup.
+ candidates.size == 1 ? candidates.first : nil
end
# Finds a pending transaction using fuzzy amount matching for tip adjustments
diff --git a/app/models/enable_banking_account/processor.rb b/app/models/enable_banking_account/processor.rb
index 2d575e6138..a0a4d6c19d 100644
--- a/app/models/enable_banking_account/processor.rb
+++ b/app/models/enable_banking_account/processor.rb
@@ -40,6 +40,13 @@ class EnableBankingAccount::Processor
enable_banking_account.update_column(:balance_verified, false) if enable_banking_account.persisted?
raise
end
+
+ # Skipped only when the batch itself raised. A run with single failed rows
+ # (success: false) still cleans up: both steps only touch pendings that
+ # already have a booked twin or are older than 8 days, and gating on
+ # success would stop the cleanup for good behind one row that keeps failing.
+ clean_up_pending_transactions unless @transactions_failed
+ transactions_ok
end
private
@@ -175,10 +182,27 @@ class EnableBankingAccount::Processor
def process_transactions
EnableBankingAccount::Transactions::Processor.new(enable_banking_account).process[:success]
rescue => e
+ @transactions_failed = true
report_exception(e, "transactions")
false
end
+ # Same safety net SimpleFIN runs after each import: a pending entry the import
+ # could not claim unambiguously is excluded once its booked twin shows up, and
+ # a pending that never booked within 8 days is excluded. The latter is marked,
+ # because some ASPSPs keep the same id when a pending books: the import then
+ # re-activates the entry instead of leaving it excluded and pending.
+ def clean_up_pending_transactions
+ account = enable_banking_account.current_account
+
+ Entry.reconcile_pending_duplicates(account: account)
+ Entry.auto_exclude_stale_pending(account: account, mark: true)
+ rescue => e
+ Rails.logger.warn("EnableBankingAccount::Processor - pending cleanup failed for account #{account&.id}: #{e.class} - #{e.message}")
+ capture_debug_log("Pending transaction cleanup failed: #{e.class} - #{e.message}", account) if account
+ report_exception(e, "pending_cleanup")
+ end
+
def report_exception(error, context)
Sentry.capture_exception(error) do |scope|
scope.set_tags(
diff --git a/app/models/entry.rb b/app/models/entry.rb
index 52a54cf574..edbf99f802 100644
--- a/app/models/entry.rb
+++ b/app/models/entry.rb
@@ -11,6 +11,9 @@ class Entry < ApplicationRecord
DESCRIPTIVE_ATTRIBUTES = %w[name notes updated_at].freeze
DESCRIPTIVE_TRANSACTION_ATTRIBUTES = %w[category_id merchant_id updated_at].freeze
+ # Key in transactions.extra marking a stale pending the sync excluded on its own.
+ AUTO_EXCLUDED_PENDING_KEY = "auto_excluded_stale_pending".freeze
+
attr_accessor :unsplitting
monetize :amount
@@ -86,6 +89,13 @@ class Entry < ApplicationRecord
before_destroy :prevent_individual_child_deletion, if: :split_child?
after_save :track_earliest_saved_date, if: :saved_change_to_date?
+ # Any other write of `excluded` (a user toggling it, a reconciliation) ends the
+ # "excluded automatically" state, so a later booking cannot override it. This
+ # also covers a write of the same value, e.g. a user excluding the entry from a
+ # page loaded before the sync excluded it.
+ before_save :clear_auto_excluded_pending_mark, if: -> { @excluded_assigned }
+ after_save -> { @excluded_assigned = false }
+
# Split rows in the order they were entered. Without an ORDER BY PostgreSQL
# returns them in physical order, which shifts as rows are rewritten.
scope :in_split_order, -> { order(:created_at, :id) }
@@ -241,19 +251,47 @@ class Entry < ApplicationRecord
# Called during sync to clean up pending transactions that never posted
# @param account [Account] The account to clean up
# @param days [Integer] Number of days after which pending is considered stale (default: 8)
+ # @param mark [Boolean] Remember on the transaction that the exclusion was automatic,
+ # so an import that later books the same bank id can re-activate the entry
+ # (see Account::ProviderImportAdapter). Entries excluded by the user carry no mark.
# @return [Integer] Number of entries excluded
- def self.auto_exclude_stale_pending(account:, days: 8)
+ def self.auto_exclude_stale_pending(account:, days: 8, mark: false)
stale_entries = account.entries.stale_pending(days: days).where(excluded: false)
count = stale_entries.count
if count > 0
- stale_entries.update_all(excluded: true, updated_at: Time.current)
- Rails.logger.info("Auto-excluded #{count} stale pending transaction(s) for account #{account.id} (#{account.name})")
+ if mark
+ transaction do
+ # Re-check under a row lock: an entry the user excluded, or the import
+ # claimed, since the query above keeps its state and gets no mark.
+ # Transactions first, then entries: the same order as a Transaction
+ # save, which touches its entry, so the two cannot deadlock.
+ transaction_ids = Transaction.where(id: stale_entries.select(:entryable_id)).order(:id).lock.pluck(:id)
+ ids = stale_entries.where(entryable_id: transaction_ids).order(:id).lock("FOR UPDATE OF entries").pluck(:id)
+
+ Transaction.where(id: Entry.where(id: ids).select(:entryable_id))
+ .update_all([ "extra = COALESCE(extra, '{}'::jsonb) || jsonb_build_object(?::text, true)", AUTO_EXCLUDED_PENDING_KEY ])
+ count = Entry.where(id: ids).update_all(excluded: true, updated_at: Time.current)
+ end
+ else
+ stale_entries.update_all(excluded: true, updated_at: Time.current)
+ end
+ Rails.logger.info("Auto-excluded #{count} stale pending transaction(s) for account #{account.id} (#{account.name})") if count > 0
end
count
end
+ def excluded=(value)
+ @excluded_assigned = true
+ super
+ end
+
+ # True for a pending entry that auto_exclude_stale_pending(mark: true) excluded.
+ def auto_excluded_pending?
+ excluded? && entryable.is_a?(Transaction) && entryable.extra&.dig(AUTO_EXCLUDED_PENDING_KEY) == true
+ end
+
# Retroactively reconcile pending transactions that have a matching posted version
# This handles duplicates created before reconciliation code was deployed
#
@@ -282,6 +320,7 @@ class Entry < ApplicationRecord
.where.not(id: pending_entry.id)
.where(currency: pending_entry.currency)
.where(amount: pending_entry.amount)
+ .where(source: pending_entry.source) # one provider's pending is never another provider's duplicate
.where(date: pending_entry.date..(pending_entry.date + date_window.days)) # Posted must be ON or AFTER pending date
.where(not_pending_sql)
.limit(2) # Only need to know if 0, 1, or 2+ candidates
@@ -289,7 +328,13 @@ class Entry < ApplicationRecord
# Handle exact match - auto-exclude only if exactly ONE candidate (high confidence)
# Multiple candidates = ambiguous = skip to avoid excluding wrong entry
+ # The posted match must also be unambiguous the other way round: two
+ # same-amount pendings would otherwise both be excluded against one booking,
+ # hiding the one that has not booked yet (#2013).
if exact_candidates.size == 1
+ # Also no fuzzy suggestion then: it would point every pending at the same booking.
+ next unless sole_pending_for?(exact_candidates.first, date_window: date_window)
+
posted_match = exact_candidates.first
detail = {
pending_id: pending_entry.id,
@@ -312,6 +357,8 @@ class Entry < ApplicationRecord
end
next
end
+ # Two exact bookings: a name match would just pick one of them at random.
+ next if exact_candidates.size > 1
# PRIORITY 2: If no exact match, try fuzzy amount match for tip adjustments
# Store as SUGGESTION instead of auto-excluding (medium confidence)
@@ -324,6 +371,7 @@ class Entry < ApplicationRecord
.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
.where.not(id: pending_entry.id)
.where(currency: pending_entry.currency)
+ .where(source: pending_entry.source)
.where(date: pending_entry.date..(pending_entry.date + fuzzy_date_window.days)) # Posted ON or AFTER pending
.where("ABS(entries.amount) BETWEEN ? AND ?", min_amount, max_amount)
.where(not_pending_sql)
@@ -386,6 +434,21 @@ class Entry < ApplicationRecord
stats
end
+ # True when no other live pending could claim this posted entry: the same
+ # amount/currency lookup Account::ProviderImportAdapter#find_pending_transaction
+ # runs at import time, seen from the posted side.
+ def self.sole_pending_for?(posted_entry, date_window:)
+ posted_entry.account.entries.pending
+ .where(excluded: false)
+ .where(currency: posted_entry.currency)
+ .where(amount: posted_entry.amount)
+ .where(source: posted_entry.source)
+ .where(date: (posted_entry.date - date_window.days)..posted_entry.date)
+ .limit(2)
+ .count == 1
+ end
+ private_class_method :sole_pending_for?
+
def classification
amount.negative? ? "income" : "expense"
end
@@ -828,6 +891,19 @@ class Entry < ApplicationRecord
end
private
+ # Works on the stored row: the loaded transaction may predate the sync
+ # that wrote the mark.
+ def clear_auto_excluded_pending_mark
+ return unless entryable_type == "Transaction" && entryable_id
+
+ Transaction.where(id: entryable_id).where("transactions.extra ->> ? IS NOT NULL", AUTO_EXCLUDED_PENDING_KEY)
+ .update_all([ "extra = extra - ?::text", AUTO_EXCLUDED_PENDING_KEY ])
+
+ if association(:entryable).loaded? && entryable.extra&.key?(AUTO_EXCLUDED_PENDING_KEY)
+ entryable.extra = entryable.extra.except(AUTO_EXCLUDED_PENDING_KEY)
+ end
+ end
+
# Takes FOR UPDATE on the transaction row, then on this entry (lock! also reloads both), always
# in that order so the split methods can't deadlock each other. Yields the transaction, or nil
# for other entryables.
diff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rb
index 46900f70fc..3afc29efca 100644
--- a/test/models/account/provider_import_adapter_test.rb
+++ b/test/models/account/provider_import_adapter_test.rb
@@ -1882,8 +1882,9 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase
end
end
- test "reconciles most recent pending when multiple exist" do
- # Create two pending transactions with same amount
+ test "does not auto-claim pending when multiple same-amount candidates exist" do
+ # Two distinct pendings with the same amount: amount/date alone cannot tell
+ # which one the posted transaction belongs to (#2013).
older_pending = @adapter.import_transaction(
external_id: "simplefin_older_pending",
amount: 60.00,
@@ -1904,8 +1905,7 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase
extra: { "simplefin" => { "pending" => true } }
)
- # Import posted - should match the most recent pending (by date)
- assert_no_difference "@account.entries.count" do
+ assert_difference "@account.entries.count", 1 do
posted_entry = @adapter.import_transaction(
external_id: "simplefin_posted_recurring",
amount: 60.00,
@@ -1916,11 +1916,85 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCase
extra: { "simplefin" => { "pending" => false } }
)
- # Should match the newer pending entry
- assert_equal newer_pending.id, posted_entry.id
- # Older pending should remain untouched
- assert_equal "simplefin_older_pending", older_pending.reload.external_id
+ assert_not_includes [ older_pending.id, newer_pending.id ], posted_entry.id
end
+
+ assert_equal "simplefin_older_pending", older_pending.reload.external_id
+ assert_equal "simplefin_newer_pending", newer_pending.reload.external_id
+ assert newer_pending.transaction.pending?
+ end
+
+ test "keeps a distinct same-amount pending when another one is ambiguous (#2013)" do
+ # Two $20 ATM withdrawals pending, only one posts: neither pending may be
+ # overwritten, otherwise the other withdrawal's external_id is lost for good.
+ first = @adapter.import_transaction(
+ external_id: "enable_banking_atm_1",
+ amount: 20.00,
+ currency: "USD",
+ date: Date.today - 2.days,
+ name: "ATM Withdrawal",
+ source: "enable_banking",
+ extra: { "enable_banking" => { "pending" => true } }
+ )
+ second = @adapter.import_transaction(
+ external_id: "enable_banking_atm_2",
+ amount: 20.00,
+ currency: "USD",
+ date: Date.today - 1.day,
+ name: "ATM Withdrawal",
+ source: "enable_banking",
+ extra: { "enable_banking" => { "pending" => true } }
+ )
+
+ posted_entry = @adapter.import_transaction(
+ external_id: "enable_banking_atm_booked",
+ amount: 20.00,
+ currency: "USD",
+ date: Date.today,
+ name: "ATM Withdrawal",
+ source: "enable_banking",
+ extra: { "enable_banking" => { "pending" => false } }
+ )
+
+ assert posted_entry.transaction.extra["auto_claimed_pending_ids"].blank?
+ assert_equal "enable_banking_atm_1", first.reload.external_id
+ assert_equal "enable_banking_atm_2", second.reload.external_id
+ end
+
+ test "does not claim an excluded pending" do
+ excluded_pending = @adapter.import_transaction(
+ external_id: "simplefin_excluded_pending",
+ amount: 35.00,
+ currency: "USD",
+ date: Date.today - 3.days,
+ name: "Old Hold",
+ source: "simplefin",
+ extra: { "simplefin" => { "pending" => true } }
+ )
+ excluded_pending.update!(excluded: true)
+
+ live_pending = @adapter.import_transaction(
+ external_id: "simplefin_live_pending",
+ amount: 35.00,
+ currency: "USD",
+ date: Date.today - 1.day,
+ name: "Live Hold",
+ source: "simplefin",
+ extra: { "simplefin" => { "pending" => true } }
+ )
+
+ posted_entry = @adapter.import_transaction(
+ external_id: "simplefin_posted_hold",
+ amount: 35.00,
+ currency: "USD",
+ date: Date.today,
+ name: "Hold Posted",
+ source: "simplefin",
+ extra: { "simplefin" => { "pending" => false } }
+ )
+
+ assert_equal live_pending.id, posted_entry.id
+ assert_equal "simplefin_excluded_pending", excluded_pending.reload.external_id
end
# Every provider in Transaction::PENDING_PROVIDERS must be reconcilable, not just the
diff --git a/test/models/enable_banking_account/processor_test.rb b/test/models/enable_banking_account/processor_test.rb
index d7f4467b6b..8d3699e22c 100644
--- a/test/models/enable_banking_account/processor_test.rb
+++ b/test/models/enable_banking_account/processor_test.rb
@@ -259,9 +259,145 @@ class EnableBankingAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal 50000.0, loan_account.reload.cash_balance
end
+ test "excludes pending entries older than 8 days and marks the exclusion as automatic" do
+ stale = create_pending_entry(external_id: "eb_stale_pending", date: 10.days.ago.to_date, amount: 42)
+ recent = create_pending_entry(external_id: "eb_recent_pending", date: 3.days.ago.to_date, amount: 43)
+
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+
+ assert stale.reload.excluded?
+ assert stale.auto_excluded_pending?
+ assert_not recent.reload.excluded?
+ end
+
+ test "an automatically excluded pending is re-activated when the same id is delivered as booked" do
+ stale = create_pending_entry(external_id: "eb_hold", date: 10.days.ago.to_date, amount: 80)
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+ assert stale.reload.excluded?
+
+ Account::ProviderImportAdapter.new(@account).import_transaction(
+ external_id: "eb_hold", amount: 80, currency: @account.currency, date: Date.current,
+ name: "Hotel", source: "enable_banking", extra: { "enable_banking" => { "pending" => false } }
+ )
+
+ stale.reload
+ assert_not stale.excluded?
+ assert_not stale.transaction.pending?
+ assert_not stale.auto_excluded_pending?
+ end
+
+ test "excluding or re-including an auto-excluded pending by hand ends its automatic state" do
+ stale = create_pending_entry(external_id: "eb_toggle", date: 10.days.ago.to_date, amount: 82)
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+ assert stale.reload.auto_excluded_pending?
+
+ stale.update!(excluded: false)
+ stale.update!(excluded: true)
+
+ assert_not stale.reload.auto_excluded_pending?
+ Account::ProviderImportAdapter.new(@account).import_transaction(
+ external_id: "eb_toggle", amount: 82, currency: @account.currency, date: Date.current,
+ name: "Hotel", source: "enable_banking", extra: { "enable_banking" => { "pending" => false } }
+ )
+ assert stale.reload.excluded?
+ end
+
+ test "excluding an already auto-excluded pending by hand ends its automatic state" do
+ stale = create_pending_entry(external_id: "eb_stale_page", date: 10.days.ago.to_date, amount: 85)
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+ assert stale.reload.auto_excluded_pending?
+
+ # The user excludes it from a page loaded before the sync did.
+ stale.update!(excluded: true)
+
+ assert_not stale.reload.auto_excluded_pending?
+ Account::ProviderImportAdapter.new(@account).import_transaction(
+ external_id: "eb_stale_page", amount: 85, currency: @account.currency, date: Date.current,
+ name: "Hotel", source: "enable_banking", extra: { "enable_banking" => { "pending" => false } }
+ )
+ assert stale.reload.excluded?
+ end
+
+ test "excluding by hand clears the mark even when the transaction was loaded before the sync" do
+ stale = create_pending_entry(external_id: "eb_preloaded", date: 10.days.ago.to_date, amount: 86)
+ loaded = Entry.includes(:entryable).find(stale.id)
+ loaded.entryable.extra # loaded before the sync writes the mark
+
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+ assert stale.reload.auto_excluded_pending?
+
+ loaded.update!(excluded: true)
+
+ assert_not stale.reload.auto_excluded_pending?
+ end
+
+ test "a pending the user excluded stays excluded when it books" do
+ stale = create_pending_entry(external_id: "eb_user_excluded", date: 10.days.ago.to_date, amount: 81)
+ stale.update!(excluded: true)
+
+ Account::ProviderImportAdapter.new(@account).import_transaction(
+ external_id: "eb_user_excluded", amount: 81, currency: @account.currency, date: Date.current,
+ name: "Hotel", source: "enable_banking", extra: { "enable_banking" => { "pending" => false } }
+ )
+
+ assert stale.reload.excluded?
+ end
+
+ test "an import-locked auto-excluded pending stays excluded when it books" do
+ stale = create_pending_entry(external_id: "eb_locked", date: 10.days.ago.to_date, amount: 83)
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+ stale.reload.update_columns(import_locked: true)
+
+ Account::ProviderImportAdapter.new(@account).import_transaction(
+ external_id: "eb_locked", amount: 83, currency: @account.currency, date: Date.current,
+ name: "Hotel", source: "enable_banking", extra: { "enable_banking" => { "pending" => false } }
+ )
+
+ assert stale.reload.excluded?
+ assert stale.auto_excluded_pending?
+ end
+
+ test "excludes a pending entry once its booked twin exists" do
+ pending = create_pending_entry(external_id: "eb_pending", date: 3.days.ago.to_date, amount: 25)
+ @account.entries.create!(
+ name: "Coffee", date: 1.day.ago.to_date, amount: 25, currency: @account.currency,
+ external_id: "eb_booked", source: "enable_banking",
+ entryable: Transaction.new(extra: { "enable_banking" => { "pending" => false } })
+ )
+
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+
+ assert pending.reload.excluded?
+ end
+
+ test "skips the pending cleanup when importing transactions failed" do
+ stale = create_pending_entry(external_id: "eb_partial", date: 10.days.ago.to_date, amount: 84)
+ EnableBankingAccount::Transactions::Processor.any_instance.stubs(:process).raises(StandardError, "boom")
+
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+
+ assert_not stale.reload.excluded?
+ end
+
+ test "pending cleanup failure does not fail processing" do
+ Entry.stubs(:reconcile_pending_duplicates).raises(StandardError, "boom")
+
+ assert_nothing_raised do
+ EnableBankingAccount::Processor.new(@enable_banking_account).process
+ end
+ end
+
private
def relink_provider_to(account)
AccountProvider.find_by(provider: @enable_banking_account)&.destroy
AccountProvider.create!(account: account, provider: @enable_banking_account)
end
+
+ def create_pending_entry(external_id:, date:, amount:)
+ @account.entries.create!(
+ name: "Pending #{external_id}", date: date, amount: amount, currency: @account.currency,
+ external_id: external_id, source: "enable_banking",
+ entryable: Transaction.new(extra: { "enable_banking" => { "pending" => true } })
+ )
+ end
end
diff --git a/test/models/entry_test.rb b/test/models/entry_test.rb
index 64faa6c607..8176e1cc1d 100644
--- a/test/models/entry_test.rb
+++ b/test/models/entry_test.rb
@@ -420,6 +420,79 @@ class EntryTest < ActiveSupport::TestCase
assert entry.saved_changes_affect_balances?
end
+ test "reconcile_pending_duplicates excludes a pending with one unambiguous booked match" do
+ account = accounts(:depository)
+ pending = create_pending(account, date: 3.days.ago.to_date, amount: 25)
+ create_transaction(account: account, date: 1.day.ago.to_date, amount: 25)
+
+ Entry.reconcile_pending_duplicates(account: account)
+
+ assert pending.reload.excluded?
+ end
+
+ test "reconcile_pending_duplicates keeps both same-amount pendings when only one booked" do
+ account = accounts(:depository)
+ first = create_pending(account, date: 3.days.ago.to_date, amount: 20)
+ second = create_pending(account, date: 2.days.ago.to_date, amount: 20)
+ create_transaction(account: account, date: 1.day.ago.to_date, amount: 20)
+
+ Entry.reconcile_pending_duplicates(account: account)
+
+ assert_not first.reload.excluded?
+ assert_not second.reload.excluded?
+ end
+
+ test "reconcile_pending_duplicates suggests no fuzzy match when the exact match is ambiguous" do
+ account = accounts(:depository)
+ first = create_pending(account, date: 3.days.ago.to_date, amount: 5)
+ second = create_pending(account, date: 2.days.ago.to_date, amount: 5)
+ first.update!(name: "Starbucks Store")
+ second.update!(name: "Starbucks Store")
+ create_transaction(account: account, date: 1.day.ago.to_date, amount: 5, name: "Starbucks Store")
+
+ Entry.reconcile_pending_duplicates(account: account)
+
+ assert_nil first.reload.transaction.extra["potential_posted_match"]
+ assert_nil second.reload.transaction.extra["potential_posted_match"]
+ end
+
+ test "reconcile_pending_duplicates suggests no fuzzy match when two bookings match exactly" do
+ account = accounts(:depository)
+ pending = create_pending(account, date: 3.days.ago.to_date, amount: 5)
+ pending.update!(name: "Starbucks Store")
+ create_transaction(account: account, date: 2.days.ago.to_date, amount: 5, name: "Starbucks Store")
+ create_transaction(account: account, date: 1.day.ago.to_date, amount: 5, name: "Card payment")
+
+ Entry.reconcile_pending_duplicates(account: account)
+
+ assert_not pending.reload.excluded?
+ assert_nil pending.transaction.extra["potential_posted_match"]
+ end
+
+ test "reconcile_pending_duplicates ignores a booked entry from another provider" do
+ account = accounts(:depository)
+ pending = create_pending(account, date: 3.days.ago.to_date, amount: 30)
+ pending.update_columns(source: "simplefin")
+ booked = create_transaction(account: account, date: 1.day.ago.to_date, amount: 30)
+ booked.update_columns(source: "lunchflow")
+
+ Entry.reconcile_pending_duplicates(account: account)
+
+ assert_not pending.reload.excluded?
+ end
+
+ test "reconcile_pending_duplicates does not suggest a fuzzy match from another provider" do
+ account = accounts(:depository)
+ pending = create_pending(account, date: 3.days.ago.to_date, amount: 30)
+ pending.update_columns(source: "simplefin")
+ booked = create_transaction(account: account, date: 2.days.ago.to_date, amount: 33)
+ booked.update_columns(source: "lunchflow")
+
+ Entry.reconcile_pending_duplicates(account: account)
+
+ assert_nil pending.reload.transaction.extra["potential_posted_match"]
+ end
+
test "balance update scopes split reconciliations from every other entry" do
account = accounts(:connected)
account.entries.destroy_all
@@ -432,4 +505,12 @@ class EntryTest < ActiveSupport::TestCase
assert_equal [ transaction, opening_anchor, current_anchor ].map(&:id).sort,
account.entries.excluding_balance_updates.pluck(:id).sort
end
+
+ private
+ def create_pending(account, date:, amount:)
+ create_transaction(
+ account: account, date: date, amount: amount,
+ entryable: Transaction.new(extra: { "simplefin" => { "pending" => true } })
+ )
+ end
end