The personal finance app for everyone (by everyone)
Ruby
Generate and backfill logos for website-only provider merchants (#3776)
GFR1ce861a9b07e
diff --git a/app/models/family.rb b/app/models/family.rbindex 9d5d8018f9..4ec45ba836 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -423,6 +423,19 @@ class Family < ApplicationRecordMerchant.where(id: merchant_ids)end+ # Generates missing Brandfetch logos for provider merchants that have a+ # website, so records that got their website before Brandfetch was configured+ # self-heal (issue #2925). Returns the number of logos generated.+ #+ # Logos are cosmetic: a failure here must not fail the callers (post-sync+ # rule application, LLM merchant enhancement).+ def backfill_provider_merchant_logos+ ProviderMerchant.where(id: transactions.select(:merchant_id)).backfill_logos+ rescue StandardError => e+ Rails.logger.error("Failed to backfill provider merchant logos for family #{id}: #{e.message}")+ 0+ end+def available_merchantsassigned_ids = transactions.where.not(merchant_id: nil).pluck(:merchant_id).uniqrecently_unlinked_ids = FamilyMerchantAssociationdiff --git a/app/models/family/auto_merchant_detector.rb b/app/models/family/auto_merchant_detector.rbindex d74e47a4b6..a7776316fd 100644--- a/app/models/family/auto_merchant_detector.rb+++ b/app/models/family/auto_merchant_detector.rb@@ -69,10 +69,6 @@ class Family::AutoMerchantDetectorProvider::Registry.preferred_llm_providerend- def default_logo_provider_url- "https://cdn.brandfetch.io"- end-def user_merchants_inputfamily.merchants.map do |merchant|{@@ -152,15 +148,10 @@ class Family::AutoMerchantDetectordef enhance_provider_merchant(merchant, auto_detection)updates = {}- # Add website_url if missing+ # Add website_url if missing. ProviderMerchant fills a blank logo from it+ # and keeps a provider-supplied one (issue #2925).if merchant.website_url.blank? && auto_detection.business_url.present?updates[:website_url] = auto_detection.business_url-- # Add logo if BrandFetch is configured- if Setting.brand_fetch_client_id.present?- size = Setting.brand_fetch_logo_size- updates[:logo_url] = "#{default_logo_provider_url}/#{auto_detection.business_url}/icon/fallback/lettermark/w/#{size}/h/#{size}?c=#{Setting.brand_fetch_client_id}"- endendreturn false if updates.empty?diff --git a/app/models/family/syncer.rb b/app/models/family/syncer.rbindex ee1c7de069..67df952b94 100644--- a/app/models/family/syncer.rb+++ b/app/models/family/syncer.rb@@ -21,6 +21,7 @@ class Family::Syncerdef perform_post_syncfamily.auto_match_transfers!+ family.backfill_provider_merchant_logosRails.logger.info("Applying rules for family #{family.id}")ApplyRulesJob.perform_later(family)diff --git a/app/models/family_merchant.rb b/app/models/family_merchant.rbindex 11462d60de..cd11a7b60e 100644--- a/app/models/family_merchant.rb+++ b/app/models/family_merchant.rb@@ -44,9 +44,7 @@ class FamilyMerchant < Merchantdef generate_logo_url_from_websiteif website_url.present? && Setting.brand_fetch_client_id.present?- domain = extract_domain(website_url)- size = Setting.brand_fetch_logo_size- self.logo_url = "https://cdn.brandfetch.io/#{domain}/icon/fallback/lettermark/w/#{size}/h/#{size}?c=#{Setting.brand_fetch_client_id}"+ self.logo_url = Setting.brand_fetch_icon_url(extract_domain(website_url))elsif website_url.blank?self.logo_url = nilenddiff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rbindex 9976bca6e4..e5ac37e449 100644--- a/app/models/provider_merchant.rb+++ b/app/models/provider_merchant.rb@@ -1,6 +1,10 @@class ProviderMerchant < Merchantenum :source, { plaid: "plaid", simplefin: "simplefin", lunchflow: "lunchflow", akahu: "akahu", up: "up", monobank: "monobank", synth: "synth", ai: "ai", enable_banking: "enable_banking", coinstats: "coinstats", mercury: "mercury", brex: "brex", indexa_capital: "indexa_capital", sophtron: "sophtron", questrade: "questrade", redbark: "redbark", fio: "fio" }+ # Unlike FamilyMerchant, only fill a blank logo: providers such as Plaid or+ # CoinStats supply their own logo_url, which must not be replaced (issue #2925).+ before_save :generate_logo_url_from_website, if: :should_generate_logo?+validates :name, uniqueness: { scope: [ :source ] }validates :source, presence: true@@ -41,6 +45,32 @@ class ProviderMerchant < Merchant# because the accessors and the hook above have already discarded any value.validates :color, absence: true+ # Merchants that have a website but no logo, e.g. because the website arrived+ # from a provider or the LLM before Brandfetch was configured.+ scope :missing_logo, -> { where.not(website_url: [ nil, "" ]).where(logo_url: [ nil, "" ]) }++ # Generates Brandfetch logos for merchants in the current scope that have a+ # website but no logo. Needs no LLM. Returns the number of logos generated.+ def self.backfill_logos+ return 0 if Setting.brand_fetch_client_id.blank?++ missing_logo.find_each.count do |merchant|+ generated = false++ merchant.with_lock do+ if merchant.logo_url.blank?+ merchant.save!+ generated = merchant.logo_url.present?+ end+ end++ generated+ rescue ActiveRecord::RecordInvalid => e+ Rails.logger.warn("Failed to backfill logo for merchant #{merchant.id}: #{e.message}")+ false+ end+ end+# Convert this ProviderMerchant to a FamilyMerchant for a specific family.# Only affects transactions belonging to that family.# Returns the newly created FamilyMerchant.@@ -82,11 +112,14 @@ class ProviderMerchant < Merchantend# Generate logo URL from website_url using BrandFetch, if configured.+ # Only refreshes or clears a logo generated here: a provider-supplied logo+ # (Plaid, CoinStats) must not be replaced (issue #2925), while a Brandfetch+ # logo must follow the website it was derived from.def generate_logo_url_from_website!+ return unless logo_url.blank? || brandfetch_logo?+if website_url.present? && Setting.brand_fetch_client_id.present?- domain = extract_domain(website_url)- size = Setting.brand_fetch_logo_size- update!(logo_url: "https://cdn.brandfetch.io/#{domain}/icon/fallback/lettermark/w/#{size}/h/#{size}?c=#{Setting.brand_fetch_client_id}")+ update!(logo_url: brandfetch_logo_url)elsif website_url.blank?update!(logo_url: nil)end@@ -111,6 +144,31 @@ class ProviderMerchant < Merchantprivate+ def should_generate_logo?+ website_url.present? && logo_url.blank?+ end++ def generate_logo_url_from_website+ self.logo_url = brandfetch_logo_url+ end++ # Ties ownership to our own Brandfetch account id, not just the CDN host,+ # so a provider-supplied logo that merely happens to be hosted on+ # cdn.brandfetch.io (e.g. under the provider's own account) is never+ # mistaken for one this app generated.+ def brandfetch_logo?+ client_id = Setting.brand_fetch_client_id+ return false if client_id.blank?++ logo_url.to_s.start_with?("https://cdn.brandfetch.io/") && logo_url.include?("?c=#{client_id}")+ end++ def brandfetch_logo_url+ return nil if website_url.blank?++ Setting.brand_fetch_icon_url(extract_domain(website_url))+ end+def extract_domain(url)normalized_url = url.start_with?("http://", "https://") ? url : "https://#{url}"URI.parse(normalized_url).host&.sub(/\Awww\./, "")diff --git a/app/models/provider_merchant/enhancer.rb b/app/models/provider_merchant/enhancer.rbindex 059241eabe..a9f2353db0 100644--- a/app/models/provider_merchant/enhancer.rb+++ b/app/models/provider_merchant/enhancer.rb@@ -12,8 +12,12 @@ class ProviderMerchant::Enhancerenddef enhance- return { enhanced: 0, deduplicated: 0 } unless llm_provider- return { enhanced: 0, deduplicated: 0 } if unenhanced_merchants.none?+ # Runs before the LLM checks: generating a logo from a known website needs no+ # LLM, and merchants that already have a website are never sent to it (issue #2925).+ logos = @family.backfill_provider_merchant_logos++ return { enhanced: 0, deduplicated: 0, logos: logos } unless llm_provider+ return { enhanced: 0, deduplicated: 0, logos: logos } if unenhanced_merchants.none?Rails.logger.info("Enhancing #{unenhanced_merchants.count} provider merchants for family #{@family.id}")@@ -35,10 +39,9 @@ class ProviderMerchant::Enhancernext unless merchantnext if merchant.website_url.present? # Skip if already enhanced (race condition guard)- # Step 1: Update the provider merchant with website + logo- updates = { website_url: enhancement.business_url }- updates[:logo_url] = build_logo_url(enhancement.business_url) if Setting.brand_fetch_client_id.present?- merchant.update!(updates)+ # Step 1: Update the provider merchant's website. ProviderMerchant generates+ # the Brandfetch logo itself, keeping a logo the provider already supplied.+ merchant.update!(website_url: enhancement.business_url)enhanced_count += 1# Step 2: Deduplicate — find other merchants with the same website_url@@ -51,7 +54,7 @@ class ProviderMerchant::EnhancerRails.logger.info("Enhanced #{enhanced_count} merchants, deduplicated #{deduplicated_count} for family #{@family.id}")- { enhanced: enhanced_count, deduplicated: deduplicated_count }+ { enhanced: enhanced_count, deduplicated: deduplicated_count, logos: logos }endprivate@@ -91,19 +94,4 @@ class ProviderMerchant::Enhancerscope.to_aendend-- def build_logo_url(business_url)- return nil unless Setting.brand_fetch_client_id.present? && business_url.present?- domain = extract_domain(business_url)- return nil unless domain.present?- size = Setting.brand_fetch_logo_size- "https://cdn.brandfetch.io/#{domain}/icon/fallback/lettermark/w/#{size}/h/#{size}?c=#{Setting.brand_fetch_client_id}"- end-- def extract_domain(url)- normalized_url = url.start_with?("http://", "https://") ? url : "https://#{url}"- URI.parse(normalized_url).host&.sub(/\Awww\./, "")- rescue URI::InvalidURIError- url.sub(/\Awww\./, "")- endenddiff --git a/docs/hosting/logos.md b/docs/hosting/logos.mdindex 4cc77ee9c6..494a5b1987 100644--- a/docs/hosting/logos.md+++ b/docs/hosting/logos.md@@ -1,10 +1,10 @@# Account, Merchant and Security Logos-Sure has integration with the [Brandfetch Logo Link](https://brandfetch.com/developers/logo-api) service to provide logos for accounts, merchants and securities.+Sure supports custom account icons and integrates with the [Brandfetch Logo Link](https://brandfetch.com/developers/logo-api) service to provide logos for accounts, merchants and securities.Logos are currently matched in the following ways:-- For accounts, Plaid integration for the account is required and matched via FQDN (fully qualified domain name) from the Plaid integration-- For merchants, OpenAI integration is required and automatically matched to the merchant name and matched via FQDN+- For accounts, icons are discovered using the institution domain, supplied by a bank sync provider or entered manually. In the account form under **Additional details → Icon**, you can pick an icon from the App Store, Google Play, RuStore or favicon services, upload your own image, or choose Brandfetch when configured. Plaid is not required; uploads and discovery from other services work without a Brandfetch Client ID. Uploaded or manually picked icons are preserved during automatic updates.+- For merchants, logos are matched via the merchant's website FQDN. The website comes from the bank sync provider (e.g. Plaid, Akahu) or from an AI provider that matches it to the merchant name. A logo the provider already supplies is kept- For securities, logos are matched using the ticker symbol> [!NOTE]@@ -17,4 +17,6 @@ A Brandfetch Client ID is required and to obtain a client ID, sign up for an accOnce you enter the Client ID into the Sure settings under the `Self-Hosting` section, logos from Brandfetch integration will be enabled.Alternatively, you can provide the client id using the `BRAND_FETCH_CLIENT_ID` environment variable to the web and worker services.+Merchants that already have a website but no logo, for example because they were matched before the Client ID was configured, get their logo on the next sync.+diff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex 2fd20d75e9..2bc4eacfc8 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -553,6 +553,21 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseendend+ # Issue #2925: Akahu (and sometimes Plaid) supply a website but no logo.+ test "creates a website-only merchant with a Brandfetch logo" do+ Setting.stubs(:brand_fetch_client_id).returns("test_client_id")+ Setting.stubs(:brand_fetch_logo_size).returns(40)++ merchant = @adapter.find_or_create_merchant(+ provider_merchant_id: "akahu_merchant_123",+ name: "Countdown",+ source: "akahu",+ website_url: "https://www.countdown.co.nz"+ )++ assert_equal "https://cdn.brandfetch.io/countdown.co.nz/icon/fallback/lettermark/w/40/h/40?c=test_client_id", merchant.logo_url+ end+test "returns nil when merchant data is insufficient" domerchant = @adapter.find_or_create_merchant(provider_merchant_id: "",diff --git a/test/models/family/auto_merchant_detector_test.rb b/test/models/family/auto_merchant_detector_test.rbindex cfa0da7d37..b1e638d41c 100644--- a/test/models/family/auto_merchant_detector_test.rb+++ b/test/models/family/auto_merchant_detector_test.rb@@ -177,6 +177,39 @@ class Family::AutoMerchantDetectorTest < ActiveSupport::TestCaseassert_equal known.id, txn.reload.merchant.idend+ test "enhancing a provider merchant keeps its provider-supplied logo" do+ provider_logo = "https://plaid-merchant-logos.plaid.com/coffee_shop.png"+ merchant = ProviderMerchant.create!(source: "plaid", name: "Coffee Shop", logo_url: provider_logo)+ txn = create_transaction(account: @account, name: "COFFEE SHOP 123", merchant: merchant).transaction++ provider_response = provider_success_response([+ AutoDetectedMerchant.new(transaction_id: txn.id, business_name: "Coffee Shop", business_url: "https://www.coffeeshop.com")+ ])++ @llm_provider.expects(:auto_detect_merchants).returns(provider_response).once++ Family::AutoMerchantDetector.new(@family, transaction_ids: [ txn.id ]).auto_detect++ merchant.reload+ assert_equal "https://www.coffeeshop.com", merchant.website_url+ assert_equal provider_logo, merchant.logo_url+ end++ test "enhancing a provider merchant without a logo builds the logo from the website's domain" do+ merchant = ProviderMerchant.create!(source: "plaid", name: "Book Store")+ txn = create_transaction(account: @account, name: "BOOK STORE 42", merchant: merchant).transaction++ provider_response = provider_success_response([+ AutoDetectedMerchant.new(transaction_id: txn.id, business_name: "Book Store", business_url: "https://www.bookstore.com")+ ])++ @llm_provider.expects(:auto_detect_merchants).returns(provider_response).once++ Family::AutoMerchantDetector.new(@family, transaction_ids: [ txn.id ]).auto_detect++ assert_equal "https://cdn.brandfetch.io/bookstore.com/icon/fallback/lettermark/w/40/h/40?c=123", merchant.reload.logo_url+ end+privateAutoDetectedMerchant = Provider::LlmConcept::AutoDetectedMerchantenddiff --git a/test/models/family/syncer_test.rb b/test/models/family/syncer_test.rbindex 71f768db4e..e1865c88bd 100644--- a/test/models/family/syncer_test.rb+++ b/test/models/family/syncer_test.rb@@ -62,6 +62,22 @@ class Family::SyncerTest < ActiveSupport::TestCaseassert_no_enqueued_jobs(only: RuleJob)end+ # Issue #2925: merchants whose website arrived before Brandfetch was+ # configured get their logo on the next sync.+ test "backfills provider merchant logos after sync" do+ @family.expects(:backfill_provider_merchant_logos).once++ Family::Syncer.new(@family).perform_post_sync+ end++ test "a logo backfill failure does not stop rules from being applied" do+ ProviderMerchant.stubs(:backfill_logos).raises(StandardError, "boom")++ assert_enqueued_with(job: ApplyRulesJob, args: [ @family ]) do+ Family::Syncer.new(@family).perform_post_sync+ end+ end+privatedef syncable_item_associationsFamily.reflect_on_all_associations(:has_many).select do |association|diff --git a/test/models/provider_merchant/enhancer_test.rb b/test/models/provider_merchant/enhancer_test.rbindex 0f17f078f6..beb0ff2c19 100644--- a/test/models/provider_merchant/enhancer_test.rb+++ b/test/models/provider_merchant/enhancer_test.rb@@ -131,6 +131,69 @@ class ProviderMerchant::EnhancerTest < ActiveSupport::TestCaseassert_equal 0, result[:enhanced]end+ # Issue #2925: a website that arrived before Brandfetch was configured left the+ # merchant without a logo, and the enhancer never selected it again.+ test "backfills logos for merchants that already have a website without calling the LLM" do+ merchant = ProviderMerchant.create!(source: "akahu", name: "Amazon", provider_merchant_id: "ak_amazon", website_url: "amazon.com")+ merchant.update_column(:logo_url, nil)+ create_transaction(account: @account, name: "Amazon order", merchant: merchant)++ @llm_provider.expects(:enhance_provider_merchants).never++ result = ProviderMerchant::Enhancer.new(@family).enhance++ assert_equal 1, result[:logos]+ assert_equal "https://cdn.brandfetch.io/amazon.com/icon/fallback/lettermark/w/40/h/40?c=test_client_id", merchant.reload.logo_url+ end++ test "backfills logos without an LLM provider" do+ Provider::Registry.stubs(:get_provider).with(:openai).returns(nil)+ Provider::Registry.stubs(:get_provider).with(:anthropic).returns(nil)+ merchant = ProviderMerchant.create!(source: "ai", name: "Amazon", website_url: "amazon.com")+ merchant.update_column(:logo_url, nil)+ create_transaction(account: @account, name: "Amazon order", merchant: merchant)++ result = ProviderMerchant::Enhancer.new(@family).enhance++ assert_equal 1, result[:logos]+ assert merchant.reload.logo_url.present?+ end++ # A logo backfill failure is cosmetic and must not abort the enhance run —+ # otherwise it would skip LLM enhancement and deduplication for the family.+ test "a logo backfill failure does not prevent enhancement" do+ merchant = ProviderMerchant.create!(source: "lunchflow", name: "Walmart", provider_merchant_id: "lf_walmart")+ create_transaction(account: @account, name: "Walmart purchase", merchant: merchant)+ ProviderMerchant.stubs(:backfill_logos).raises(StandardError, "boom")++ provider_response = provider_success_response([+ EnhancedMerchant.new(merchant_id: merchant.id, business_url: "walmart.com")+ ])+ @llm_provider.expects(:enhance_provider_merchants).returns(provider_response).once++ result = ProviderMerchant::Enhancer.new(@family).enhance++ assert_equal 0, result[:logos]+ assert_equal 1, result[:enhanced]+ assert_equal "walmart.com", merchant.reload.website_url+ end++ test "keeps a provider-supplied logo when adding the website" do+ merchant = ProviderMerchant.create!(source: "coinstats", name: "Binance", provider_merchant_id: "cs_binance", logo_url: "https://coinstats.app/binance.png")+ create_transaction(account: @account, name: "Binance transfer", merchant: merchant)++ provider_response = provider_success_response([+ EnhancedMerchant.new(merchant_id: merchant.id, business_url: "binance.com")+ ])+ @llm_provider.expects(:enhance_provider_merchants).returns(provider_response).once++ result = ProviderMerchant::Enhancer.new(@family).enhance++ assert_equal 1, result[:enhanced]+ assert_equal "binance.com", merchant.reload.website_url+ assert_equal "https://coinstats.app/binance.png", merchant.logo_url+ end+privateEnhancedMerchant = Provider::LlmConcept::EnhancedMerchantenddiff --git a/test/models/provider_merchant_test.rb b/test/models/provider_merchant_test.rbindex 627291f468..395f9e6f65 100644--- a/test/models/provider_merchant_test.rb+++ b/test/models/provider_merchant_test.rb@@ -106,6 +106,161 @@ class ProviderMerchantTest < ActiveSupport::TestCaseassert_nil @provider_merchant.reload.colorend+ # Issue #2925: provider merchants that arrive with a website but no logo must+ # get a Brandfetch logo, without replacing a logo the provider supplied.+ test "generates a Brandfetch logo for a website-only merchant" do+ with_brandfetch do+ merchant = ProviderMerchant.create!(name: "Walmart", source: "akahu", website_url: "https://www.walmart.com")++ assert_equal brandfetch_logo("walmart.com"), merchant.logo_url+ end+ end++ test "keeps a provider-supplied logo" do+ with_brandfetch do+ merchant = ProviderMerchant.create!(name: "Walmart", source: "plaid", website_url: "walmart.com", logo_url: "https://plaid.com/walmart.png")++ assert_equal "https://plaid.com/walmart.png", merchant.logo_url+ end+ end++ test "leaves the logo blank without Brandfetch" do+ Setting.stubs(:brand_fetch_client_id).returns(nil)++ merchant = ProviderMerchant.create!(name: "Walmart", source: "akahu", website_url: "walmart.com")++ assert_nil merchant.logo_url+ end++ # Regression: the Settings edit path calls generate_logo_url_from_website!+ # explicitly after a website change; it must not replace a provider-supplied+ # logo with the Brandfetch fallback (issue #2925).+ test "generate_logo_url_from_website! keeps a provider-supplied logo" do+ with_brandfetch do+ merchant = ProviderMerchant.create!(name: "Walmart", source: "plaid", website_url: "walmart.com", logo_url: "https://plaid.com/walmart.png")++ merchant.update!(website_url: "walmart.de")+ merchant.generate_logo_url_from_website!+ assert_equal "https://plaid.com/walmart.png", merchant.reload.logo_url++ merchant.update!(website_url: nil)+ merchant.generate_logo_url_from_website!+ assert_equal "https://plaid.com/walmart.png", merchant.reload.logo_url+ end+ end++ # Regression: a provider-supplied logo hosted on the Brandfetch CDN itself+ # (e.g. under the provider's own account) must not be mistaken for a logo+ # this app generated just because the host matches (issue #2925).+ test "generate_logo_url_from_website! keeps a provider-supplied logo hosted on the Brandfetch CDN" do+ with_brandfetch do+ provider_supplied = "https://cdn.brandfetch.io/walmart.com/icon/fallback/lettermark/w/40/h/40?c=some_other_account_id"+ merchant = ProviderMerchant.create!(name: "Walmart", source: "plaid", website_url: "walmart.com", logo_url: provider_supplied)++ merchant.update!(website_url: "walmart.de")+ merchant.generate_logo_url_from_website!++ assert_equal provider_supplied, merchant.reload.logo_url+ end+ end++ test "generate_logo_url_from_website! refreshes a Brandfetch logo after a website change" do+ with_brandfetch do+ merchant = ProviderMerchant.create!(name: "Walmart", source: "ai", website_url: "walmart.com")+ assert_equal brandfetch_logo("walmart.com"), merchant.logo_url++ merchant.update!(website_url: "walmart.de")+ merchant.generate_logo_url_from_website!++ assert_equal brandfetch_logo("walmart.de"), merchant.reload.logo_url+ end+ end++ test "generate_logo_url_from_website! clears a Brandfetch logo when the website is removed" do+ with_brandfetch do+ merchant = ProviderMerchant.create!(name: "Walmart", source: "ai", website_url: "walmart.com")++ merchant.update!(website_url: nil)+ merchant.generate_logo_url_from_website!++ assert_nil merchant.reload.logo_url+ end+ end++ test "backfill_logos fills website-only merchants in scope and counts them" do+ Setting.stubs(:brand_fetch_client_id).returns(nil) # the websites arrived before Brandfetch was configured+ website_only = ProviderMerchant.create!(name: "Walmart", source: "ai", website_url: "walmart.com")+ out_of_scope = ProviderMerchant.create!(name: "Target", source: "ai", website_url: "target.com")+ with_logo = ProviderMerchant.create!(name: "Costco", source: "plaid", website_url: "costco.com", logo_url: "https://plaid.com/costco.png")++ with_brandfetch do+ scope = ProviderMerchant.where(id: [ website_only.id, with_logo.id, @provider_merchant.id ])++ assert_equal 1, scope.backfill_logos+ end++ assert_equal brandfetch_logo("walmart.com"), website_only.reload.logo_url+ assert_nil out_of_scope.reload.logo_url+ assert_equal "https://plaid.com/costco.png", with_logo.reload.logo_url+ assert_nil @provider_merchant.reload.logo_url+ end++ # Regression: a provider sync can write a real provider logo between the time+ # backfill_logos loads a merchant and when it saves the Brandfetch fallback.+ # The lock-and-recheck must keep the provider logo instead of overwriting it.+ test "backfill_logos does not clobber a logo written concurrently by a provider sync" do+ Setting.stubs(:brand_fetch_client_id).returns(nil) # the website arrived before Brandfetch was configured+ merchant = ProviderMerchant.create!(name: "Walmart", source: "ai", website_url: "walmart.com")++ # find_each yields a freshly loaded instance, not `merchant`, so the stub has+ # to live on the class (restored after) rather than on this one object.+ original_with_lock = ProviderMerchant.instance_method(:with_lock)+ ProviderMerchant.define_method(:with_lock) do |&block|+ if id == merchant.id+ self.class.where(id: id).update_all(logo_url: "https://provider.example.com/walmart.png")+ end+ original_with_lock.bind(self).call(&block)+ end++ with_brandfetch do+ assert_equal 0, ProviderMerchant.where(id: merchant.id).backfill_logos+ end++ assert_equal "https://provider.example.com/walmart.png", merchant.reload.logo_url+ ensure+ ProviderMerchant.define_method(:with_lock, original_with_lock) if original_with_lock+ end++ test "backfill_logos does nothing without Brandfetch" do+ merchant = ProviderMerchant.create!(name: "Walmart", source: "ai", website_url: "walmart.com")+ Setting.stubs(:brand_fetch_client_id).returns(nil)++ assert_equal 0, ProviderMerchant.backfill_logos+ assert_nil merchant.reload.logo_url+ end++ test "family backfill only touches merchants on the family's transactions" do+ Setting.stubs(:brand_fetch_client_id).returns(nil) # the websites arrived before Brandfetch was configured+ assigned = ProviderMerchant.create!(name: "Walmart", source: "ai", website_url: "walmart.com")+ unassigned = ProviderMerchant.create!(name: "Target", source: "ai", website_url: "target.com")+ create_transaction(merchant: assigned)++ with_brandfetch do+ assert_equal 1, @family.backfill_provider_merchant_logos+ end++ assert_equal brandfetch_logo("walmart.com"), assigned.reload.logo_url+ assert_nil unassigned.reload.logo_url+ end++ # Logos are cosmetic: a backfill failure must not propagate to the callers+ # (post-sync rule application, LLM merchant enhancement).+ test "family backfill returns 0 when the backfill fails" do+ ProviderMerchant.stubs(:backfill_logos).raises(StandardError, "boom")++ assert_equal 0, @family.backfill_provider_merchant_logos+ end+test "convert_to_family_merchant_for clears a website submitted blank and inherits an omitted one" do@provider_merchant.update!(website_url: "https://acme.example")@@ -161,4 +316,18 @@ class ProviderMerchantTest < ActiveSupport::TestCaseassert_equal existing.id, converted.idassert_equal "#4da568", existing.reload.colorend++ private+ def with_brandfetch+ Setting.stubs(:brand_fetch_client_id).returns("test_client_id")+ Setting.stubs(:brand_fetch_logo_size).returns(40)+ yield+ ensure+ Setting.unstub(:brand_fetch_client_id)+ Setting.unstub(:brand_fetch_logo_size)+ end++ def brandfetch_logo(domain)+ "https://cdn.brandfetch.io/#{domain}/icon/fallback/lettermark/w/40/h/40?c=test_client_id"+ endend