Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
3.9 KB
Raw Blame
class ProviderMerchant::Enhancer
  def initialize(family, merchant_ids: nil)
    @family = family
    @merchant_ids = merchant_ids
  end

  # The unenhanced merchant ids, one batch per LLM call.
  def batches
    return [] unless llm_provider

    unenhanced_merchants.map(&:id).each_slice(Provider::LlmConcept.max_items_per_call).to_a
  end

  def enhance
    # 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}")

    enhanced_count = 0
    deduplicated_count = 0

    unenhanced_merchants.each_slice(Provider::LlmConcept.max_items_per_call) do |batch|
      result = llm_provider.enhance_provider_merchants(
        merchants: batch.map { |m| { id: m.id, name: m.name } },
        family: @family
      )

      next unless result.success?

      result.data.each do |enhancement|
        next unless enhancement.business_url.present?

        merchant = batch.find { |m| m.id == enhancement.merchant_id }
        next unless merchant
        next if merchant.website_url.present? # Skip if already enhanced (race condition guard)

        # 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
        # and merge them INTO this provider merchant (prefer provider over AI)
        deduplicated_count += deduplicate_by_website(merchant, enhancement.business_url)
      rescue ActiveRecord::RecordInvalid => e
        Rails.logger.error("Failed to enhance merchant #{merchant.id}: #{e.message}")
      end
    end

    Rails.logger.info("Enhanced #{enhanced_count} merchants, deduplicated #{deduplicated_count} for family #{@family.id}")

    { enhanced: enhanced_count, deduplicated: deduplicated_count, logos: logos }
  end

  private

    def deduplicate_by_website(target_merchant, website_url)
      # Find duplicate provider merchants assigned to this family with the same website_url.
      # Excludes FamilyMerchants — user-curated merchants should never be touched by dedup.
      duplicates = @family.assigned_merchants
                          .where(type: "ProviderMerchant")
                          .where(website_url: website_url)
                          .where.not(id: target_merchant.id)

      return 0 if duplicates.none?

      count = 0
      duplicates.each do |duplicate|
        # Reassign family's transactions from duplicate to target
        @family.transactions.where(merchant_id: duplicate.id)
               .update_all(merchant_id: target_merchant.id)
        count += 1
      end
      count
    end

    # Honors Setting.llm_provider (issue #2113) — Provider::Anthropic implements
    # enhance_provider_merchants (PR #1984), so merchant enhancement routes to the
    # configured provider, with fallback handled by
    # Provider::Registry.preferred_llm_provider. Nil while the router says the
    # family may not enhance merchants, its consent included.
    def llm_provider
      return @llm_provider if defined?(@llm_provider)

      @llm_provider = (Provider::Registry.preferred_llm_provider if Ai.available?(:enhance_merchants, family: @family))
    end

    def unenhanced_merchants
      @unenhanced_merchants ||= begin
        scope = @family.assigned_merchants.where(type: "ProviderMerchant").where(website_url: [ nil, "" ])
        scope = scope.where(id: @merchant_ids) if @merchant_ids
        scope.to_a
      end
    end
end