Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
18.9 KB
Raw Blame
class Security < ApplicationRecord
  include Provided, PlanRestrictionTracker

  # Transient attribute for search results -- not persisted
  attr_accessor :search_currency, :search_isin

  # ISO 10383 MIC codes mapped to user-friendly exchange names
  # Source: https://www.iso20022.org/market-identifier-codes
  # Data stored in config/exchanges.yml
  EXCHANGES = YAML.safe_load_file(Rails.root.join("config", "exchanges.yml")).freeze

  # Legacy non-ISO values previously persisted as exchange_operating_mic
  # (e.g. raw EODHD exchange codes) mapped to their ISO MIC.
  MIC_ALIASES = {
    "WAR" => "XWAR",
    "GER" => "XETR", # Yahoo search code for Xetra, stored before it was mapped
    # Yahoo search codes for Canadian venues, stored before they were mapped
    "VAN" => "XTSX", "CNQ" => "XCNQ", "NEO" => "NEOE",
    # Raw EODHD codes that Provider::Eodhd still accepts for rows stored before it mapped them
    "F" => "XFRA", "BR" => "XBRU", "LS" => "XLIS", "VI" => "XWBO", "IR" => "XDUB",
    "BE" => "XBER", "DU" => "XDUS", "HM" => "XHAM", "HA" => "XHAN", "MU" => "XMUN", "STU" => "XSTU"
  }.freeze

  KINDS = %w[standard cash].freeze

  # Known securities provider keys — derived from the registry so adding a new
  # provider to Registry#available_providers automatically allows it here.
  # Evaluated at runtime (not boot) so runtime-enabled providers are accepted.
  def self.valid_price_providers
    Provider::Registry.for_concept(:securities).provider_keys.map(&:to_s)
  end

  # Builds the Brandfetch crypto URL for a base asset (e.g. "BTC"). Returns
  # nil when Brandfetch isn't configured.
  # The symbol goes into a URL path segment, and it comes from provider data —
  # an on-chain token can be called anything its deployer chose. A slash, a
  # question mark or a hash would not merely break the link: they would point
  # the path elsewhere on the CDN, or push the client id into a fragment where
  # Brandfetch never sees it. Guarded here rather than at each call site, since
  # six of them reach this method from four different providers.
  SAFE_CRYPTO_SYMBOL = /\A[A-Za-z0-9][A-Za-z0-9.\-]{0,31}\z/

  def self.brandfetch_crypto_url(base_asset)
    return nil if base_asset.blank?
    return nil unless base_asset.to_s.match?(SAFE_CRYPTO_SYMBOL)

    Setting.brand_fetch_icon_url(base_asset, namespace: "crypto")
  end

  # Classification taxonomy: the six-class / twelve-sub-class scheme other
  # portfolio trackers use, so an import maps onto it without a translation
  # table. The database enforces the same sets (chk_securities_asset_class,
  # chk_securities_asset_sub_class, chk_securities_classification_source);
  # adding a value means changing both, deliberately.
  #
  # Schema only for now: nothing writes these columns yet, so every security
  # is unclassified (NULL) until a later drop populates them.
  #
  # The migration repeats these lists rather than reading them from here, so
  # that it produces the same schema whenever it runs. Changing a list is
  # therefore a two-file edit, and "the model taxonomy and the database
  # constraint list the same values" fails if only one side moves.
  #
  # `sector` and `industry` have no constants and no validation on purpose:
  # they hold provider vocabulary, which no two providers agree on. An
  # `inclusion` rule there would reject a value a provider legitimately
  # returns.
  #
  # `region` is NOT the same case, and grouping it with those two would be
  # wrong. No provider supplies a region -- they supply a country, and the
  # region is derived from it against a list this application owns -- so its
  # vocabulary is closed and a model-level `inclusion` validation is the right
  # enforcement once something writes it. It is unconstrained today only
  # because nothing does. It is left unconstrained in the DATABASE for a
  # different reason: the list belongs in configuration, where widening it
  # should not need a migration. The migration header says the same.
  ASSET_CLASSES = %w[
    alternative_investment commodity equity fixed_income liquidity real_estate
  ].freeze

  ASSET_SUB_CLASSES = %w[
    bond cash collectible commodity cryptocurrency etf loan mutual_fund
    precious_metal private_equity real_estate stock
  ].freeze

  # Same shape as Holding's cost-basis provenance: who set the classification,
  # so a later writer knows whether it may replace it. `classification_locked`
  # is the user's veto over every source.
  CLASSIFICATION_SOURCES = %w[provider manual ai default].freeze

  before_validation :upcase_symbols
  before_save :generate_logo_url_from_brandfetch, if: :should_generate_logo?
  before_save :reset_first_provider_price_on_if_provider_changed

  has_many :trades, dependent: :nullify, class_name: "Trade"
  has_many :prices, dependent: :destroy
  has_many :splits, dependent: :destroy
  # A security row is shared by every family that holds the instrument, but a
  # Tag belongs to one family, so a tagging is reachable only through its
  # owning family's tags. Read one family's with #tags_for and write them with
  # #set_tags_for. There is deliberately no `has_many :tags, through:`: its
  # generated `tags=`, `tag_ids=` and `tags <<` know nothing about families,
  # and would delete other families' taggings or attach a tag the family does
  # not own.
  has_many :taggings, as: :taggable, dependent: :destroy

  validates :ticker, presence: true
  validates :ticker, uniqueness: { scope: :exchange_operating_mic, case_sensitive: false }
  validates :kind, inclusion: { in: KINDS }
  validates :price_provider, inclusion: { in: ->(_) { Security.valid_price_providers } }, allow_nil: true
  validates :asset_class, inclusion: { in: ASSET_CLASSES }, allow_nil: true
  validates :asset_sub_class, inclusion: { in: ASSET_SUB_CLASSES }, allow_nil: true
  validates :classification_source, inclusion: { in: CLASSIFICATION_SOURCES }, allow_nil: true

  scope :online, -> { where(offline: false) }
  scope :standard, -> { where(kind: "standard") }

  # Parses the combobox ID format "SYMBOL|EXCHANGE|PROVIDER" into a hash.
  def self.parse_combobox_id(value)
    parts = value.to_s.split("|", 3)
    { ticker: parts[0].presence, exchange_operating_mic: parts[1].presence, price_provider: parts[2].presence }
  end

  # Lazily finds or creates a synthetic cash security for an account.
  # Used as fallback when creating an interest Trade without a user-selected
  # security, and to represent non-primary-currency cash positions as holdings
  # (issue #1809). When a currency that differs from the account's primary
  # currency is given, a distinct per-currency security is created so balances
  # in different currencies don't collide.
  def self.cash_for(account, currency: nil)
    distinct = currency.present? && currency.to_s.upcase != account.currency.to_s.upcase
    ticker = (distinct ? "CASH-#{account.id}-#{currency}" : "CASH-#{account.id}").upcase
    find_or_create_by!(ticker: ticker, kind: "cash") do |s|
      s.name = distinct ? "Cash (#{currency.to_s.upcase})" : "Cash"
      s.offline = true
    end
  end

  def cash?
    kind == "cash"
  end

  # `family`'s tags on this security, and no other family's.
  def tags_for(family)
    family.tags.where(id: taggings.select(:tag_id))
  end

  # Moves this security's taggings onto `canonical` when the two are merged.
  # A tag `canonical` already carries stays here and goes with this
  # security's destroy!, as the unique index on taggings allows only one.
  def move_taggings_to!(canonical)
    transaction do
      # The same row lock set_tags_for takes, on both securities in a stable
      # order, so a concurrent tag edit on either waits for the move.
      Security.where(id: [ id, canonical.id ]).order(:id).lock.load

      taggings.where(<<~SQL, canonical.id).update_all(taggable_id: canonical.id)
        NOT EXISTS (
          SELECT 1 FROM taggings carried
          WHERE carried.taggable_type = 'Security'
            AND carried.taggable_id = ?
            AND carried.tag_id = taggings.tag_id
        )
      SQL
      taggings.reset
    end
  end

  # Replaces only `family`'s tags on this security.
  #
  # A wholesale replace would delete other families' taggings on the same
  # instrument, because the row is shared. Ids are resolved through
  # `family.tags` rather than `Tag`, so a tag this family does not own is
  # never attached: that would show its name to every family holding the
  # security.
  #
  # Lock order is security (FOR UPDATE), then tags (FOR SHARE), then taggings.
  # `Tag#replace_and_destroy!` takes taggings then the tag, so the two can
  # deadlock on the same security and tag, and PostgreSQL then aborts one of
  # them with a deadlock error. A new writer should take the locks in this
  # order.
  def set_tags_for(family, tag_ids)
    # `with_lock` reloads the row, which an unsaved security does not have.
    raise ArgumentError, "save the security before tagging it" unless persisted?

    mine = family.tags.select(:id)

    # A check-then-insert on a row every family shares. The unique index on
    # taggings refuses a duplicate, so without the lock two concurrent saves
    # of the same tag would fail one of them rather than both succeed. The
    # lock also reloads the record, so no stale association survives.
    with_lock do
      # Read inside the lock and FOR SHARE: the security's row lock does not
      # cover the tags, so without it a tag deleted between this read and the
      # insert below would fail the insert. A concurrent delete of a wanted
      # tag now waits for this write to commit.
      wanted = family.tags.where(id: Array(tag_ids).reject(&:blank?)).lock("FOR SHARE").pluck(:id)

      taggings.where(tag_id: mine).where.not(tag_id: wanted).destroy_all
      already = taggings.where(tag_id: wanted).pluck(:tag_id)
      (wanted - already).each { |id| taggings.create!(tag_id: id) }
    end
  end

  # True when this security represents a crypto asset. Today the only signal
  # is the Binance ISO MIC — when we add a second crypto provider, extend
  # this check rather than duplicating the test at every call site.
  def crypto?
    exchange_operating_mic == Provider::BinancePublic::BINANCE_MIC
  end

  # Strips the display-currency suffix from a crypto ticker (BTCUSD -> BTC,
  # ETHEUR -> ETH). Returns nil for non-crypto securities or when the ticker
  # doesn't end in a supported quote.
  def crypto_base_asset
    return nil unless crypto?

    # Delegated rather than parsed here: this stripped a fiat suffix only, so it
    # answered nil for the "CRYPTO:BTC" form the holdings processors store — the
    # form every crypto integration writes — and those securities carried no
    # logo at all. The provider already parses every shape it accepts.
    Provider::BinancePublic.parse_ticker(ticker)&.dig(:base)
  end

  # Single source of truth for which logo URL the UI should render.
  # - Crypto keeps its dedicated Brandfetch-crypto shape.
  # - When a website domain is known, Brandfetch (consistent client_id + size)
  #   wins, falling back to any stored logo_url.
  # - With no domain, a stored provider logo (e.g. T-Invest's CDN for MOEX
  #   instruments) is authoritative and beats the ticker-only Brandfetch
  #   lettermark placeholder.
  # A stored Brandfetch logo_url is rewritten to the current size and client
  # id, since holdings and the API render this value without transforming it.
  def display_logo_url
    if crypto?
      self.class.brandfetch_crypto_url(crypto_base_asset).presence || stored_logo_url
    elsif website_url.present?
      brandfetch_icon_url.presence || stored_logo_url
    else
      stored_logo_url || brandfetch_icon_url.presence
    end
  end

  # Returns user-friendly exchange name for a MIC code
  def self.exchange_name_for(mic)
    return nil if mic.blank?
    EXCHANGES.dig(mic.upcase, "name") || mic.upcase
  end

  def self.canonical_exchange_operating_mic(mic)
    return nil if mic.blank?

    key = mic.to_s.upcase
    MIC_ALIASES.fetch(key, key)
  end

  # Values that should match the same venue for DB lookup (canonical + legacy aliases).
  def self.exchange_operating_mic_lookup_values(mic)
    return [] if mic.blank?

    canonical = canonical_exchange_operating_mic(mic)
    aliases = MIC_ALIASES.select { |_legacy, canon| canon == canonical }.keys
    ([ canonical ] + aliases).uniq
  end

  # Finds a security by ticker + MIC, treating legacy MIC aliases as the same
  # venue. When a legacy row is found, upgrades it to the canonical MIC unless
  # a canonical row already exists (in which case the canonical row wins).
  #
  # When +exchange_operating_mic+ is blank:
  # - match_blank_mic: true  → only rows with a blank MIC (find-or-initialize)
  # - match_blank_mic: false → do not filter by MIC (exact DB match by ticker)
  def self.find_by_ticker_and_exchange(ticker:, exchange_operating_mic: nil, country_code: nil, match_blank_mic: false)
    return nil if ticker.blank?

    scope = where("UPPER(ticker) = ?", ticker.to_s.upcase)

    if exchange_operating_mic.present?
      mics = exchange_operating_mic_lookup_values(exchange_operating_mic)
      scope = scope.where("UPPER(exchange_operating_mic) IN (?)", mics)
    elsif match_blank_mic
      scope = scope.where(exchange_operating_mic: [ nil, "" ])
    end

    scope = scope.where(country_code: country_code) if country_code.present?

    canonical = canonical_exchange_operating_mic(exchange_operating_mic)
    security = if canonical.present?
      scope.order(
        Arel.sql(
          sanitize_sql_array([
            "CASE WHEN UPPER(COALESCE(exchange_operating_mic, '')) = ? THEN 0 ELSE 1 END",
            canonical
          ])
        )
      ).first
    else
      scope.first
    end

    return nil unless security
    return security if canonical.blank?
    return security if security.exchange_operating_mic.to_s.upcase == canonical

    existing_canonical = find_by(ticker: security.ticker, exchange_operating_mic: canonical)
    return existing_canonical if existing_canonical

    security.update!(exchange_operating_mic: canonical)
    security
  end

  def self.find_or_initialize_by_ticker_and_exchange(ticker:, exchange_operating_mic: nil)
    existing = find_by_ticker_and_exchange(
      ticker: ticker,
      exchange_operating_mic: exchange_operating_mic,
      match_blank_mic: exchange_operating_mic.blank?
    )
    return existing if existing

    new(
      ticker: ticker,
      exchange_operating_mic: canonical_exchange_operating_mic(exchange_operating_mic)
    )
  end

  def exchange_name
    self.class.exchange_name_for(exchange_operating_mic)
  end

  def current_price
    @current_price ||= find_or_fetch_price
    return nil if @current_price.nil?
    Money.new(@current_price.price, @current_price.currency)
  end

  # The current price in `currency`. A quote comes in the listing's currency,
  # which need not be the one a trade or position is carried in. Converted at
  # the quote's own date, as the holdings are. nil when there is no price or no
  # rate to convert it at, rather than the unconverted figure read as if it
  # were in `currency`. Memoised per currency, a miss included, because a page
  # asks for the same figure more than once and a missing rate is a provider
  # call each time.
  #
  # A page listing several securities passes one `rates` hash to all of them,
  # so quotes in the same currency on the same day share one rate lookup
  # instead of each making its own.
  def current_price_in(currency, rates: {})
    @current_price_in ||= {}
    return @current_price_in[currency] if @current_price_in.key?(currency)

    price = current_price
    @current_price_in[currency] = price && convert_quote(price, currency, rates)
  end

  # Stores user-supplied closes for a security no provider tracks. See Security::ManualPriceImport.
  def import_manual_prices!(rows, accounts:)
    Security::ManualPriceImport.new(security: self, rows: rows, accounts: accounts).import!
  end

  # How many shares one share held at the close of `from` has become by the
  # close of `to`: the product of the ratios of splits whose ex-date falls
  # after `from` and on or before `to`. 1 when there are none.
  def split_factor_between(from, to)
    splits.where(ex_date: (from + 1)..to).reduce(Rational(1)) { |factor, split| factor * split.ratio }
  end

  def to_combobox_option
    ComboboxOption.new(
      symbol: ticker,
      name: name,
      logo_url: logo_url,
      exchange_operating_mic: exchange_operating_mic,
      country_code: country_code,
      price_provider: price_provider,
      currency: search_currency,
      isin: search_isin
    )
  end

  def brandfetch_icon_url(width: nil, height: nil)
    identifier = extract_domain(website_url) if website_url.present?
    identifier ||= ticker

    Setting.brand_fetch_icon_url(identifier, width: width, height: height)
  end

  private
    def convert_quote(price, currency, rates)
      to = Money::Currency.new(currency).iso_code
      return price if price.currency.iso_code == to

      date = @current_price&.date || Date.current
      key = [ price.currency.iso_code, to, date ]
      rate = rates.fetch(key) do
        rates[key] = ExchangeRate.find_or_fetch_rate(from: key.first, to: to, date: date)&.rate
      end
      return nil unless rate&.positive?

      price.exchange_to(to, date: date, custom_rate: rate)
    end


    def stored_logo_url
      Setting.transform_brand_fetch_url(logo_url).presence
    end

    def extract_domain(url)
      uri = URI.parse(url)
      host = uri.host || url
      host.sub(/\Awww\./, "")
    rescue URI::InvalidURIError
      nil
    end

    def upcase_symbols
      self.ticker = ticker.upcase
      # Only canonicalize a MIC being written. A stored legacy alias is upgraded by
      # find_by_ticker_and_exchange, which checks for a canonical twin first;
      # rewriting it on an unrelated save would collide with that twin.
      if exchange_operating_mic.present? && will_save_change_to_exchange_operating_mic?
        self.exchange_operating_mic = self.class.canonical_exchange_operating_mic(exchange_operating_mic)
      end
    end

    def should_generate_logo?
      return false if cash?
      return false unless Setting.brand_fetch_client_id.present?

      return true if logo_url.blank?
      return false unless logo_url.include?("cdn.brandfetch.io")

      website_url_changed? || ticker_changed?
    end

    def generate_logo_url_from_brandfetch
      self.logo_url = if crypto?
        self.class.brandfetch_crypto_url(crypto_base_asset)
      else
        brandfetch_icon_url
      end
    end

    # When a user remaps a security to a different provider (via the holdings
    # remap combobox or Security::Resolver), the previously-discovered
    # first_provider_price_on belongs to the OLD provider and may no longer
    # reflect what the new provider can serve. Reset it so the next sync's
    # fallback rediscovers the correct earliest date for the new provider.
    # Skip when the caller explicitly set both columns in the same save.
    def reset_first_provider_price_on_if_provider_changed
      return unless price_provider_changed?
      return if first_provider_price_on_changed?
      self.first_provider_price_on = nil
    end
end