Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
3.2 KB
Raw Blame
class GoalPledge::Reconciler
  attr_reader :entry

  # `valuation_delta` is the contribution (new_balance − prior_balance) for
  # Valuation entries, supplied by Account::ReconciliationManager which knows
  # the prior balance. It is ignored for Transaction entries, whose own
  # amount is already the contribution.
  def initialize(entry, valuation_delta: nil)
    @entry = entry
    @valuation_delta = valuation_delta
  end

  # For an entry booked in the app, where the caller may already hold a
  # transaction (the API wraps trade creation in one). Waits for every open
  # transaction to commit, so a rolled-back entry never resolves a pledge
  # and a database error rescued in #run can't leave the caller's
  # transaction aborted. Runs at once when no transaction is open.
  def self.run_after_commit(entry)
    ActiveRecord.after_all_transactions_commit { new(entry).run }
  end

  def run
    return unless eligible_entry?
    return if already_stamped?

    # Older pledges resolve first. Deterministic so "first claim wins"
    # under ties doesn't depend on PK ordering (which find_each batches
    # by) — relevant the day Sure adopts ULID/UUID PKs.
    GoalPledge
      .where(account_id: entry.account_id, status: "open", kind: expected_kind)
      .where("expires_at >= ?", Time.current)
      .order(:created_at, :id)
      .each do |pledge|
      next unless pledge.matches?(entry, valuation_delta: @valuation_delta)

      begin
        if entry.entryable.is_a?(Transaction)
          pledge.resolve_with!(entry.transaction)
        elsif entry.entryable.is_a?(Trade)
          pledge.resolve_with_trade!(entry.trade)
        elsif entry.entryable.is_a?(Valuation)
          pledge.resolve_with_valuation!
        end
        Rails.logger.info("GoalPledge ##{pledge.id} matched entry ##{entry.id}")
        return
      rescue GoalPledge::NotOpenError,
             GoalPledge::AlreadyClaimedError,
             ActiveRecord::RecordInvalid,
             ActiveRecord::RecordNotUnique => e
        # Race vs another worker (this pledge got claimed, or this txn got
        # stamped by another pledge). Fall through and try the next pledge.
        Rails.logger.warn("GoalPledge ##{pledge.id} match failed: #{e.class}: #{e.message}")
      end
    end
  rescue StandardError => e
    # Don't let an unexpected reconcile failure break the importer pipeline
    # we're hooked into (ProviderImportAdapter / ReconciliationManager).
    # Surface to Sentry so the actual bug doesn't hide behind a warn-level
    # log; the inner narrow rescue handles known races without coming
    # through here.
    Rails.logger.error("GoalPledge::Reconciler failed for entry ##{entry&.id}: #{e.class}: #{e.message}")
    Sentry.capture_exception(e) if defined?(Sentry)
  end

  private
    def eligible_entry?
      return false if entry.account_id.blank?
      return false if entry.excluded?

      entry.entryable.is_a?(Transaction) || entry.entryable.is_a?(Valuation) || GoalPledge.deposit_trade?(entry)
    end

    def already_stamped?
      return false if entry.entryable.is_a?(Valuation)

      entry.entryable.extra.dig("goal", "pledge_id").present?
    end

    def expected_kind
      entry.entryable.is_a?(Valuation) ? "manual_save" : "transfer"
    end
end