Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
3.4 KB
Raw Blame
class Tag < ApplicationRecord
  COLORS = %w[#e99537 #4da568 #6471eb #db5a54 #df4e92 #c44fe9 #eb5429 #61c9ea #805dee #6ad28a]

  UNCATEGORIZED_COLOR = "#737373"

  # Tag name key for i18n
  UNTAGGED_NAME_KEY = "models.tag.untagged"

  # Stable, non-localized filter value for the synthetic "Untagged" option.
  # Using an opaque sentinel (rather than the translated display name) means a real
  # tag can never collide with it, regardless of name or locale.
  UNTAGGED_FILTER_VALUE = "__untagged__"

  belongs_to :family
  has_many :taggings, dependent: :destroy
  has_many :transactions, through: :taggings, source: :taggable, source_type: "Transaction"
  has_many :import_mappings, as: :mappable, dependent: :destroy, class_name: "Import::Mapping"

  validates :name, presence: true, uniqueness: { scope: :family }
  validates :name, exclusion: { in: [ UNTAGGED_FILTER_VALUE ] }
  validates :color, format: { with: /\A#[0-9A-Fa-f]{6}\z/ }, allow_nil: true

  scope :alphabetically, -> { order(:name, :id) }

  class << self
    def untagged
      new(name: I18n.t(UNTAGGED_NAME_KEY), color: UNCATEGORIZED_COLOR)
    end

    # Helper to get the localized name for "Untagged"
    def untagged_name
      I18n.t(UNTAGGED_NAME_KEY)
    end

    # The given tags that are on at least one of the family's transactions, as
    # a hash keyed by tag id, so a tag list can check each tag without a query
    # per row (see Category.ids_with_transactions).
    def ids_with_transactions(family:, tag_ids:)
      tag_ids = Array(tag_ids).compact
      return {} if tag_ids.empty?

      family.transactions
            .joins(:taggings)
            .where(taggings: { tag_id: tag_ids })
            .distinct
            .pluck("taggings.tag_id")
            .index_with(true)
    end
  end

  # The value the transactions-filter checkbox submits for this tag: the
  # persisted name for a real tag, or the stable sentinel for the synthetic
  # "Untagged" pseudo-tag returned by .untagged.
  def filter_value
    persisted? ? name : UNTAGGED_FILTER_VALUE
  end

  # Read-only: Security#set_tags_for is the one writer, so tagging a security
  # always takes its lock and stays inside the family.
  def securities
    Security.where(id: taggings.where(taggable_type: "Security").select(:taggable_id))
  end

  def replace_and_destroy!(replacement)
    transaction do
      raise ActiveRecord::RecordInvalid, "Replacement tag cannot be the same as the tag being destroyed" if replacement == self

      if replacement
        # Skip objects that already carry the replacement: moving their row
        # would tag them twice. Their old row goes with destroy! below. The
        # type is compared the way index_taggings_unique keys it, with a
        # missing type folded to '', so the two always agree.
        taggings.where(<<~SQL, replacement.id).update_all(tag_id: replacement.id)
          NOT EXISTS (
            SELECT 1 FROM taggings carried
            WHERE carried.tag_id = ?
              AND COALESCE(carried.taggable_type, '') = COALESCE(taggings.taggable_type, '')
              AND carried.taggable_id = taggings.taggable_id
          )
        SQL
        # A loaded taggings association still lists the moved rows, and
        # destroy! would delete them by id.
        taggings.reset
        # Properties counting this tag's transactions as costs follow them.
        Property.where(cost_tag_id: id).update_all cost_tag_id: replacement.id
      end

      destroy!
    end
  end
end