The personal finance app for everyone (by everyone)
Ruby
fix(enable-banking): use real merchant instead of POS terminal line for name (#2968)
GFR0252787dc014
diff --git a/app/models/enable_banking_account/transactions/processor.rb b/app/models/enable_banking_account/transactions/processor.rbindex 2809c6f9e5..efa525d0a2 100644--- a/app/models/enable_banking_account/transactions/processor.rb+++ b/app/models/enable_banking_account/transactions/processor.rb@@ -23,6 +23,11 @@ class EnableBankingAccount::Transactions::ProcessorAccount::ProviderImportAdapter.new(enable_banking_account.current_account)end+ # Fetch once per sync batch rather than once per transaction (each row gets its+ # own Processor instance below) -- avoids repeating the same family-scoped+ # merchant queries for every imported row.+ shared_known_merchant_names = enable_banking_account.current_account&.family&.known_merchant_names || []+# Pre-fetch external_ids that must not be re-imported.# One query per category per sync; O(1) Set lookup per transaction — avoids N+1.excluded_ids = if enable_banking_account.current_account@@ -85,7 +90,8 @@ class EnableBankingAccount::Transactions::Processorresult = EnableBankingEntry::Processor.new(transaction_data,enable_banking_account: enable_banking_account,- import_adapter: shared_adapter+ import_adapter: shared_adapter,+ known_merchant_names: shared_known_merchant_names).processif result.nil?diff --git a/app/models/enable_banking_entry/processor.rb b/app/models/enable_banking_entry/processor.rbindex 6afee84f03..93ad989ef7 100644--- a/app/models/enable_banking_entry/processor.rb+++ b/app/models/enable_banking_entry/processor.rb@@ -3,6 +3,14 @@ require "digest/md5"class EnableBankingEntry::Processorinclude CurrencyNormalizable+ # Small-merchant card terminal providers that prefix the payee with "KEYWORD *"+ PAYMENT_PROCESSOR_PREFIX = /\A(SUMUP|SQ|IZETTLE|ZETTLE|PAYPAL)\s*\*\s*/i++ # Guard against spurious matches from very short known merchant names (e.g. a+ # 2-letter FamilyMerchant name matching inside unrelated text, like "IT" would+ # inside "NAME IT" -- a real chain name observed in this issue's own data).+ MIN_KNOWN_MERCHANT_MATCH_LENGTH = 3+# enable_banking_transaction is the raw hash fetched from Enable Banking API# Transaction structure from Enable Banking:# {@@ -34,10 +42,16 @@ class EnableBankingEntry::Processor"enable_banking_content_#{Digest::MD5.hexdigest(content)}"end- def initialize(enable_banking_transaction, enable_banking_account:, import_adapter: nil)+ # known_merchant_names: optional pre-fetched Family#known_merchant_names, so a+ # caller processing many transactions in one batch (see+ # 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).+ 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_namesenddef process@@ -219,19 +233,78 @@ class EnableBankingEntry::Processorenddef primary_remittance_information+ lines = remittance_information_lines+ descriptive = lines.find { |line| !technical_remittance_line?(line) } || lines.first+ return descriptive if descriptive.blank?++ matched_known_merchant_name(descriptive) || strip_payment_processor_prefix(descriptive)+ end++ def remittance_information_linesremittance = data[:remittance_information]Array.wrap(remittance).map { |value| value.to_s.strip.presence }.compact- .first+ end++ def technical_remittance_line?(value)+ line = value.to_s.strip+ # Terminal booking line, e.g. "POS 45,13 AT D6 31.07. 10:27": require the+ # keyword+amount prefix AND the trailing date+time stamp TOGETHER, not either+ # alone. Either signal in isolation false-positives on legitimate descriptors:+ # a line like "POS 45,13 BILLA DANKT ..." (merchant appended after the amount,+ # no separate technical-only element) would wrongly match on the prefix alone,+ # and a line like "Invoice paid 31.07. 10:27" would wrongly match on the date+ # suffix alone. Requiring both matches every real technical line observed in+ # production while leaving both of those legitimate shapes untouched. Day/month+ # accept 1-2 digits (not just 2) so an un-padded ASPSP date ("1.07." instead of+ # "01.07.") is still recognized as technical.+ line.match?(/\A(POS|ATM)\s+\d+[.,]\d{2}\b.*\d{1,2}[.\/]\d{1,2}\.?\s+\d{2}:\d{2}\z/i)+ end++ def strip_payment_processor_prefix(value)+ return value if value.blank?+ value.sub(PAYMENT_PROCESSOR_PREFIX, "").strip.presence || value+ end++ # Prefer a merchant name the family already knows over any text heuristic: it's+ # already clean/trusted, and sidesteps guessing which parts of a POS line are+ # noise (store numbers, city, loyalty markers, ...) vs. part of the name.+ # Case-insensitive, whole-word match; the *stored* name (and its casing) wins,+ # so e.g. "BILLA DANKT 0007114" resolves to "Billa", not "BILLA". Longest match+ # wins when multiple known names match (prefer the more specific one).+ def matched_known_merchant_name(line)+ candidates = known_merchant_names.select { |name| name.length >= MIN_KNOWN_MERCHANT_MATCH_LENGTH }+ # Lookaround instead of \b at both ends: \b only fires on a word/non-word+ # transition, so it silently fails to match right after a name that itself+ # ends in punctuation (e.g. "A+B (Café)" ends in ")" -- a non-word char next+ # to another non-word char has no \b between them). Asserting "the boundary+ # character, if any, isn't alphanumeric" works regardless of how the known+ # name itself starts/ends.+ matches = candidates.select do |name|+ line.match?(/(?<![[:alnum:]_])#{Regexp.escape(name)}(?![[:alnum:]_])/i)+ end+ matches.max_by(&:length)+ end++ def known_merchant_names+ @known_merchant_names ||= account&.family&.known_merchant_names || []enddef merchant_name_candidatecounterparty = counterparty_name.to_s.stripreturn counterparty if counterparty.present? && !technical_card_counterparty?(counterparty)- # For technical CARD-* counterparties, reuse remittance as the best merchant candidate+remittance = primary_remittance_information- return remittance.truncate(100, omission: "") if remittance.present? && technical_card_counterparty?(counterparty)+ return nil if remittance.blank?++ # Trust remittance-derived text as a merchant candidate when either the+ # counterparty was a technical CARD-* placeholder (existing Wise case), or+ # the text matched an ALREADY-KNOWN merchant for this family. Inventing a+ # brand-new merchant from raw noisy POS text (blank counterparty, no CARD-*+ # signal, no known-merchant match) stays out of scope, unchanged from #2935.+ return remittance.truncate(100, omission: "") if technical_card_counterparty?(counterparty)+ return remittance if known_merchant_names.include?(remittance)nilenddiff --git a/app/models/family.rb b/app/models/family.rbindex cecc8a9de7..31b1b3671c 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -292,6 +292,15 @@ class Family < ApplicationRecordMerchant.where(id: (assigned_ids + recently_unlinked_ids + family_merchant_ids).uniq)end+ # Merchant names already associated with this family (via any provider, or a+ # manually created FamilyMerchant) -- used to recognize a merchant embedded in+ # noisy provider text (e.g. Enable Banking's remittance lines) without+ # inventing a new one from scratch. Deliberately excludes recently-unlinked+ # merchants (unlike available_merchants), since those were explicitly removed.+ def known_merchant_names+ (assigned_merchants.pluck(:name) + merchants.pluck(:name)).uniq+ end+def assigned_merchants_for(user)merchant_ids = Transaction.joins(:entry).where(entries: { account_id: accounts.accessible_by(user).select(:id) })diff --git a/test/models/enable_banking_entry/processor_test.rb b/test/models/enable_banking_entry/processor_test.rbindex d916e66c47..ea23331c7d 100644--- a/test/models/enable_banking_entry/processor_test.rb+++ b/test/models/enable_banking_entry/processor_test.rb@@ -1,4 +1,5 @@require "test_helper"+require "ostruct"class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCasesetup do@@ -208,6 +209,130 @@ class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCaseassert_includes entry.notes, "Détail comptable interne"end+ test "imports transaction with real merchant name instead of generic POS terminal line (issue #2935)" do+ tx = {+ entry_reference: "ref_pos_2935",+ transaction_id: nil,+ booking_date: Date.current.to_s,+ transaction_amount: { amount: "45.13", currency: "EUR" },+ creditor: { name: "" },+ debtor: nil,+ bank_transaction_code: nil,+ credit_debit_indicator: "DBIT",+ remittance_information: [+ "POS 45,13 AT D6 31.07. 10:27",+ "BILLA DANKT 0007114"+ ],+ status: "BOOK"+ }++ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process+ entry = @account.entries.find_by!(external_id: "enable_banking_ref_pos_2935")+ assert_equal "BILLA DANKT 0007114", entry.name+ assert_includes entry.notes, "POS 45,13 AT D6 31.07. 10:27"+ end++ test "uses the family's known merchant name instead of the raw remittance line when it matches, and assigns the merchant" do+ @family.merchants.create!(name: "Billa")++ tx = {+ entry_reference: "ref_known_merchant",+ transaction_id: nil,+ booking_date: Date.current.to_s,+ transaction_amount: { amount: "45.13", currency: "EUR" },+ creditor: { name: "" },+ bank_transaction_code: nil,+ credit_debit_indicator: "DBIT",+ remittance_information: [+ "POS 45,13 AT D6 31.07. 10:27",+ "BILLA DANKT 0007114"+ ],+ status: "BOOK"+ }++ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process+ entry = @account.entries.find_by!(external_id: "enable_banking_ref_known_merchant")++ assert_equal "Billa", entry.name+ assert_equal "Billa", entry.transaction.merchant&.name+ end++ test "matches known merchants regardless of retailer chain" do+ %w[Bipa Spar Hofer Lidl Penny].each do |chain_name|+ @family.merchants.create!(name: chain_name)+ end++ [+ [ "bipa", "BIPA DANKT 0001234", "Bipa" ],+ [ "spar", "SPAR DANKT 0005678", "Spar" ],+ [ "hofer", "HOFER DANKT 0009876", "Hofer" ],+ [ "lidl", "LIDL DANKT 0004321", "Lidl" ],+ [ "penny", "DANKE 0009999 PENNY", "Penny" ]+ ].each do |ref_suffix, raw_line, expected_name|+ tx = {+ entry_reference: "ref_known_#{ref_suffix}",+ transaction_id: nil,+ booking_date: Date.current.to_s,+ transaction_amount: { amount: "12.34", currency: "EUR" },+ creditor: { name: "" },+ bank_transaction_code: nil,+ credit_debit_indicator: "DBIT",+ remittance_information: [+ "POS 12,34 AT D6 01.01. 09:00",+ raw_line+ ],+ status: "BOOK"+ }++ EnableBankingEntry::Processor.new(tx, enable_banking_account: @enable_banking_account).process+ entry = @account.entries.find_by!(external_id: "enable_banking_ref_known_#{ref_suffix}")++ assert_equal expected_name, entry.name, "expected #{raw_line.inspect} to resolve to #{expected_name.inspect}"+ end+ end++ test "does not match a known merchant name shorter than the minimum match length" do+ @family.merchants.create!(name: "IT")++ name = build_name_with_family(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [ "NAME IT 1234" ]+ )++ # No known merchant match attempted ("IT" is below MIN_KNOWN_MERCHANT_MATCH_LENGTH),+ # so the line passes through unchanged.+ assert_equal "NAME IT 1234", name+ end++ test "prefers the longest matching known merchant name when multiple match" do+ @family.merchants.create!(name: "Billa")+ @family.merchants.create!(name: "Billa Corso")++ name = build_name_with_family(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [ "Billa Corso 0001234" ]+ )++ assert_equal "Billa Corso", name+ end++ test "escapes regex metacharacters in a known merchant name so matching never raises" do+ @family.merchants.create!(name: "A+B (Café)")++ name = build_name_with_family(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [ "A+B (Café) 0001234" ]+ )++ assert_equal "A+B (Café)", name+ end+test "stores exchange_rate in extra when present" dotx = {entry_reference: "ref_fx",@@ -282,13 +407,24 @@ class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCaseenddef build_processor(data)- EnableBankingEntry::Processor.new(data, enable_banking_account: Object.new)+ # A minimal stand-in that responds to current_account (real EnableBankingAccount+ # always does) so `account`/`known_merchant_names` resolve safely to nil/[] instead+ # of raising -- these unit-level tests aren't wired to a real family, so they always+ # exercise the "no known merchant" fallback path.+ EnableBankingEntry::Processor.new(data, enable_banking_account: OpenStruct.new(current_account: nil))enddef build_name(data)build_processor(data).send(:name)end+ # Unlike build_name/build_processor, wires up the real @enable_banking_account+ # (and thus the real @family) so known-merchant matching has something to match+ # against -- used by tests that create FamilyMerchant records via @family first.+ def build_name_with_family(data)+ EnableBankingEntry::Processor.new(data, enable_banking_account: @enable_banking_account).send(:name)+ end+test "skips technical card counterparty and falls back to remittance_information" doname = build_name(credit_debit_indicator: "CRDT",@@ -431,6 +567,100 @@ class EnableBankingEntry::ProcessorTest < ActiveSupport::TestCaseassert_nil processor.send(:merchant)end+ # --- technical remittance line skip (issue #2935) ---++ test "skips generic POS terminal line and uses real merchant from remittance_information" do+ name = build_name(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [+ "POS 45,13 AT D6 31.07. 10:27",+ "BILLA DANKT 0007114"+ ]+ )++ assert_equal "BILLA DANKT 0007114", name+ end++ test "skips generic ATM terminal line and uses real merchant from remittance_information" do+ name = build_name(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [+ "ATM 50,00 AT D6 31.07. 10:27",+ "SPARKASSE EISENSTADT 7000"+ ]+ )++ assert_equal "SPARKASSE EISENSTADT 7000", name+ end++ test "does not treat a POS/ATM-prefixed line as technical when it lacks a trailing date+time (merchant embedded in the same line)" do+ name = build_name(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [+ "POS 45,13 BILLA DANKT 0007114",+ "Reference 0394676"+ ]+ )++ assert_equal "POS 45,13 BILLA DANKT 0007114", name+ end++ test "does not treat a legitimate line as technical just because it ends with a date+time stamp" do+ name = build_name(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [+ "Invoice paid 31.07. 10:27",+ "Reference 0394676"+ ]+ )++ assert_equal "Invoice paid 31.07. 10:27", name+ end++ test "strips SumUp payment processor prefix from the merchant line" do+ name = build_name(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [+ "POS 130,00 AT D6 21.07. 14:20",+ "SUMUP *HERR DR. EISENSTADT 7000"+ ]+ )++ assert_equal "HERR DR. EISENSTADT 7000", name+ end++ test "falls back to the technical line when remittance_information has no descriptive line" do+ name = build_name(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [ "POS 45,13 AT D6 31.07. 10:27" ]+ )++ assert_equal "POS 45,13 AT D6 31.07. 10:27", name+ end++ test "does not treat a merchant-like line starting with POS/ATM as technical" do+ name = build_name(+ credit_debit_indicator: "DBIT",+ creditor: { name: "" },+ bank_transaction_code: nil,+ remittance_information: [ "POS Café Wien" ]+ )++ assert_equal "POS Café Wien", name+ end+test "converts unix timestamp date using family timezone not UTC" do# 2025-07-14 23:30:00 UTC == 2025-07-15 01:30:00 CEST@family.update!(timezone: "Europe/Berlin")diff --git a/test/models/family_test.rb b/test/models/family_test.rbindex d84e01759c..481a13f3e8 100644--- a/test/models/family_test.rb+++ b/test/models/family_test.rb@@ -180,6 +180,36 @@ class FamilyTest < ActiveSupport::TestCaseassert_includes family.available_merchants, new_merchantend+ test "known_merchant_names includes assigned and family-owned merchant names, deduplicates matching names, and excludes recently-unlinked merchants" do+ family = families(:dylan_family)++ provider_merchant = ProviderMerchant.create!(name: "Known Provider Merchant", source: "enable_banking")+ transactions(:one).update!(merchant: provider_merchant)++ # Same name as the assigned provider merchant, but a distinct record -- proves+ # the result is deduplicated by name value, not just by record identity.+ family.merchants.create!(name: "Known Provider Merchant")++ unassigned_family_merchant = family.merchants.create!(name: "Unassigned Family Merchant")++ # Assign then unlink a merchant -- available_merchants deliberately keeps+ # recently-unlinked merchants around (so the UI can offer a quick undo);+ # known_merchant_names must NOT, since it's used to auto-match/auto-assign new+ # transactions and re-surfacing a deliberately-removed association would undo+ # the user's action silently.+ unlinked_merchant = ProviderMerchant.create!(name: "Recently Unlinked Merchant", source: "enable_banking")+ transactions(:one).update!(merchant: unlinked_merchant)+ unlinked_merchant.unlink_from_family(family)+ transactions(:one).update!(merchant: provider_merchant)++ names = family.known_merchant_names++ assert_equal 1, names.count("Known Provider Merchant")+ assert_includes names, unassigned_family_merchant.name+ assert_not_includes names, "Recently Unlinked Merchant"+ assert_includes family.available_merchants.map(&:name), "Recently Unlinked Merchant"+ end+test "enabled currencies always include the base currency" dofamily = families(:dylan_family)family.update!(currency: "SGD", enabled_currencies: [ "USD" ])